Email sending in Spring batch

2019-09-19 17:54发布

I am very new to Spring batch. I have a requirement to send mail from my application after processing some records. Went through many links. But i did not find anything useful. Can somebody help me?

2条回答
闹够了就滚
2楼-- · 2019-09-19 18:19

Hi You can try below code, I am using this javax code in my project and working cool..

public void sendMailtoMgr(final String subject, final String message,
        String mgrmailIds) {

    String mngrecipients = null;

    Message msg = null;
    InternetAddress[] mgraddress = null;
    boolean debug = false;

    try {
      // Load your SMTP Properties from Property file
        Properties props = new Properties();
        props.put(SMTP_HOST, SMTP_HOST_VALUE);
        Session session = Session.getDefaultInstance(props, null);
        session.setDebug(debug);
        msg = new MimeMessage(session);
      // From value is nothing but from Address , can give your email id
        msg.setFrom(new InternetAddress(SMTP_FROM_VALUE));

        mngrecipients = mgrmailIds;
        mgraddress = addRecipients(mngrecipients);
        if (mgraddress != null && mgraddress.length != 0) {
        msg.setRecipients(Message.RecipientType.TO, mgraddress);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setSubject(subject);
        msg.setContent(message, "text/html");
        Transport.send(msg);

        }
    }
    catch (MessagingException mex) {
        logger.info("Exception in sendMail()");
        mex.printStackTrace();
        } 
    catch (Exception e) {
         logger.info("Exception in sendMail()", e);


    } finally {
         logger.info("Exiting sendMail()");

        }

}
查看更多
不美不萌又怎样
3楼-- · 2019-09-19 18:25

You need to implement a JobExecutionListener and add it to your job in the following manner:

<batch:job id="provisionAddOns" >
    <batch:step id="cpsProvisionAddOns">
       ...
    </batch:step>
    <batch:listeners>
        <batch:listener>
            <bean class="EmailNotification" />
        </batch:listener>
    </batch:listeners>
</batch:job>

Here EmailNotification implements JobExecutionListener and send the email in the afterJob() method; you can use any method you like to send emails depending on your needs.

查看更多
登录 后发表回答