在groovy中的异步电子邮件通知

时间:2016-09-21 11:14:01

标签: email asynchronous groovy

我在groovy类中有以下代码,我想从各种其他groovy类中异步调用此方法。

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

到目前为止,我找不到符合我要求的任何内容,有一些grails插件,但我没有使用grails。

1 个答案:

答案 0 :(得分:2)

只需使用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)
}