I have the below code in a groovy class, I want to call this method asynchronously from various other groovy classes.
public void sendNotification(){
//async true
String from = ApplicationConfig.email_From;
String sendTo = ApplicationConfig.email_To;
String host = ApplicationConfig.email_Host;
String subject = ApplicationConfig.email_Subject;
String textToSend = ApplicationConfig.email_Text;
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo));
message.setSubject(subject);
message.setText(textToSend);
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
So far I couldn't find anything that fits my requirement, there are some plugins in grails, but I'm not using grails.
Just use an ExecutorService
ExecutorService pool = Executors.newFixedThreadPool(2)
def sender = { ->
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", ApplicationConfig.email_Host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(ApplicationConfig.email_From));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(ApplicationConfig.email_To));
message.setSubject(ApplicationConfig.email_Subject);
message.setText(ApplicationConfig.email_Text);
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
public void sendNotification() {
pool.submit(sender)
}
Related
I'm trying to send emails to project managers whenever there is a change in their project staffing. For this i want to send an email from no-reply#example.com, how can i achieve this using spring boot?
Thanks in advance for the suggestions and answers.
Tried something like this:
#RequestMapping(value = "/sendEmail", method = { RequestMethod.GET }, produces = { "application/json" })
public ResponseEntity<CustomResponse> sendEmail() {
LOG.debug("Start sendEmail with data, toAddress");
HttpHeaders httpHeaders = commonUtil.setHeaders();
HttpStatus httpStatus = HttpStatus.OK;
CustomResponse customResp = new CustomResponse();
String description;
try {
String to = "bmanikanta415#gmail.com";
String from = "no-reply#example.com";
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("Your Example.com account has been activated");
msg.setText("This is a test");
Transport.send(msg);
description = Constants.SUCCESS;
customResp = commonUtil.getCustomResponse(httpStatus, description, description);
} catch (
Exception e) {
LOG.error("Exception in sendEmail: {}", e);
description = Constants.FAILED;
customResp = commonUtil.getCustomResponse(httpStatus, description, description);
}
ResponseEntity<CustomResponse> responseEntity = new ResponseEntity<CustomResponse>(customResp, httpHeaders,
httpStatus);
LOG.debug("End sendEmail with return data: {}", responseEntity);
return responseEntity;
}
Hello i would like to ask your help concerning how to send email in quartz executor. That is my code
public class SchedulerJob implements Job{
#EJB
private ParticipationTaskDao participationTaskDao;
public void sendEmail() throws AddressException, MessagingException {
List<ParticipationTask> participantTasks=participationTaskDao.listParticipantTask();
for(ParticipationTask participantTask:participantTasks){
String subject="Task";
String message="You take part to the task "+participant.getTask().getName()+" from "+participant.getTask().getDateStart()+" to "+participant.getTask().getDateEnd()+". Description:"
+ participantTask.getTask().getDescription();
String receiver=participantTask.getUser().getEmail();
System.out.println("Email sent initialisation... ");
try {
final String username="mymail#gmail.com";
final String password="mypassword";
String host = "smtp.gmail.com";
String from = "mymail#gmail.com";
String pass = "mypassword";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.debug", "true");
Session session = Session.getInstance(props, new GMailAuthenticator(username, password));
MimeMessage message = new MimeMessage(session);
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress(receiver);
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(message);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
message.saveChanges();
Transport.send(message);
transport.close();
}catch(Exception ex){
System.out.println("<html><head></head><body>");
System.out.println("ERROR: " + ex);
System.out.println("</body></html>");
}
System.out.println(""Email sent successfully);
}
}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
sendEmail();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
When i start my server, i don't see nothing but if i decide to test the below code all things runs correctly
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Quartz runs correctly");
}
The following code is supposed to send and save messages sent via yahoomail. The sending part works OK but id does not save the sent message. I've been researching and found the following code:
/**
* Read the body of the message until EOF.
*/
public static String collect(BufferedReader in) throws IOException {
String line;
StringBuffer sb = new StringBuffer();
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
return sb.toString();
}
How do I incorporate it in the following code?
public void doSendYahooMail(){
from = txtFrom.getText();
password= new String(txtPassword.getPassword());
to = txtTo.getText();
cc = txtCC.getText();
bcc = txtBCC.getText();
subject = txtSubject.getText();
message_body = jtaMessage.getText();
//String imapHost = "imap.mail.yahoo.com";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.mail.yahoo.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.imap.host", "imap.mail.yahoo.com");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.port", "993");
Session session = Session.getInstance(props,null);
try {
// message definition
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
if(!cc.equals("")){
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
}
if(!bcc.equals("")){
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
}
message.setSubject(subject);
if(!filename.equals("")){// if a file has been attached...
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message_body);// actual message
Multipart multipart = new MimeMultipart();// create multipart message
// set the text message part
multipart.addBodyPart(messageBodyPart);//add the text message to the multipart
// attachment part
messageBodyPart = new MimeBodyPart();
String attachment = fileAbsolutePath;
DataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);//add the attachment to the multipart message
// combine text and attachment
message.setContent(multipart);
// send the complete message
Transport.send(message, from, password);
}
else{// if no file has been attached
message.setText(message_body);
Transport.send(message, from, password);
}
JOptionPane.showMessageDialog(this, "Message Sent!","Sent",JOptionPane.INFORMATION_MESSAGE);
filename = "";//reset filename to null after message is sent
fileAbsolutePath = "";//reset absolute path name to null after message is sent
// save sent message
Store store = session.getStore("imap");
store.connect(from, password);
Folder folder = store.getFolder("Sent");
if(!folder.exists()){
folder.create(Folder.HOLDS_MESSAGES);
Message[] msg = new Message[1];
msg[0] = message;
folder.appendMessages(msg);
}
store.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
I have a MDB running on JBoss 7.1, and a simple Java application as a client on another machine. The goal is the following:
the client sends a request (ObjectMessage) to the server
the server processes the request and sends back a response to the client (ObjectMessage again)
I thought to use a TemporaryQueue on the client to listen for the response (because I don't know how to do it asynchronously), and the JMSReplyTo Message's property to correctly reply back because I should support multiple independent clients.
This is the client:
public class MessagingService{
private static final String JBOSS_HOST = "localhost";
private static final int JBOSS_PORT = 5455;
private static Map connectionParams = new HashMap();
private Window window;
private Queue remoteQueue;
private TemporaryQueue localQueue;
private ConnectionFactory connectionFactory;
private Connection connection;
private Session session;
public MessagingService(Window myWindow){
this.window = myWindow;
MessagingService.connectionParams.put(TransportConstants.PORT_PROP_NAME, JBOSS_PORT);
MessagingService.connectionParams.put(TransportConstants.HOST_PROP_NAME, JBOSS_HOST);
TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName(), connectionParams);
this.connectionFactory = (ConnectionFactory) HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transportConfiguration);
}
public void sendRequest(ClientRequest request) {
try {
connection = connectionFactory.createConnection();
this.session = connection.createSession(false, QueueSession.AUTO_ACKNOWLEDGE);
this.remoteQueue = HornetQJMSClient.createQueue("testQueue");
this.localQueue = session.createTemporaryQueue();
MessageProducer producer = session.createProducer(remoteQueue);
MessageConsumer consumer = session.createConsumer(localQueue);
ObjectMessage message = session.createObjectMessage();
message.setObject(request);
message.setJMSReplyTo(localQueue);
producer.send(message);
ObjectMessage response = (ObjectMessage) consumer.receive();
ServerResponse serverResponse = (ServerResponse) response.getObject();
this.window.dispatchResponse(serverResponse);
this.session.close();
} catch (JMSException e) {
// TODO splittare e differenziare
e.printStackTrace();
}
}
Now I'm having troubles writing the server side, as I cannot figure out how to establish a Connection to a TemporaryQueue...
public void onMessage(Message message) {
try {
if (message instanceof ObjectMessage) {
Destination replyDestination = message.getJMSReplyTo();
ObjectMessage objectMessage = (ObjectMessage) message;
ClientRequest request = (ClientRequest) objectMessage.getObject();
System.out.println("Queue: I received an ObjectMessage at " + new Date());
System.out.println("Client Request Details: ");
System.out.println(request.getDeparture());
System.out.println(request.getArrival());
System.out.println(request.getDate());
System.out.println("Replying...");
// no idea what to do here
Connection connection = ? ? ? ? ? ? ? ?
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer replyProducer = session.createProducer(replyDestination);
ServerResponse serverResponse = new ServerResponse("TEST RESPONSE");
ObjectMessage response = session.createObjectMessage();
response.setObject(serverResponse);
replyProducer.send(response);
} else {
System.out.println("Not a valid message for this Queue MDB");
}
} catch (JMSException e) {
e.printStackTrace();
}
}
I cannot figure out what am I missing
You are asking the wrong question here.. You should look at how to create a Connection inside any Bean.
you need to get the ConnectionFactory, and create the connection accordingly.
For more information, look at the javaee examples on the HornetQ download.
In specific look at javaee/mdb-tx-send/ when you download hornetq.
#MessageDriven(name = "MDBMessageSendTxExample",
activationConfig =
{
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/testQueue")
})
public class MDBMessageSendTxExample implements MessageListener
{
#Resource(mappedName = "java:/JmsXA")
ConnectionFactory connectionFactory;
public void onMessage(Message message)
{
Connection conn = null;
try
{
// your code here...
//Step 11. we create a JMS connection
conn = connectionFactory.createConnection();
//Step 12. We create a JMS session
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
//Step 13. we create a producer for the reply queue
MessageProducer producer = sess.createProducer(replyDestination);
//Step 14. we create a message and send it
producer.send(sess.createTextMessage("this is a reply"));
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if(conn != null)
{
try
{
conn.close();
}
catch (JMSException e)
{
}
}
}
}
I have my socket closed or reset by peer after a while,I think garbage collection problem through its reader or writer.
Asynctask for handling responses:
#Override
protected Void doInBackground(Void... params) {
//Log.e("NEW LISTENER THREAD NAME", name);
//initializations
try{
clientSocket = new Socket();
//clientSocket.setTcpNoDelay(true);
clientSocket.connect(new InetSocketAddress(serverURL, dataServerPort));
requestSender = new PrintWriter(new PrintStream(clientSocket.getOutputStream(), true,"UTF-8"));
Sender.Init();
}catch(Exception e){
e.printStackTrace();
}
gsonObj = new GsonBuilder().create();//This the object that handels every comming response
finish = false;
try{
listener = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}catch (IOException e) {
Log.e("FROM CREATING LISTENER", "FROM CREATING LISTENER ========> ");
e.printStackTrace();
}
LOGGED_IN = StaticArea.getLoggedIn(cnt);
if(LOGGED_IN){
USER = StaticArea.getUserName(cnt);
Sender.ResumeUser();
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(true);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}else{
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(false);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}
GoOnline();
while(!finish){
try{
answerS = listener.readLine();
if(answerS != null )//to avoid any null response
if(answerS.contains(Response.MYRESPONSE){
if(MyService.theHandler != null){
Message msg = new Message();
msg.obj = answerS;
MyService.theHandler.sendMessage(msg);
The Sender class is class that has a static methods and uses my sockets output:
public class Sender {
private static Gson gsonObj;
public static void Init() {
gsonObj = new GsonBuilder().create();
}
public static void SendTestRequest(){
try{
Request req = new Request();
req.setR_TYPE(Request.TEST);
String reqString = gsonObj.toJson(req);
requestSender.println(reqString);
requestSender.flush();
}catch(Exception e){
}
}//end method