DevOps Junky DevOps Junky - 2 months ago 17
Groovy Question

Asynchronous email notification in groovy

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.

Answer

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)
}