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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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()");
}
}
回答2:
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.