This post is to share with you how to send an email when you are using Spring-Batch. It was I need to do.

Spring Java Mail

Spring has many interfaces to support you to send an email by the application. A good view you can see here.

In a practical speech, you will use the MimeMessagePreparator interface to prepare the e-mail. Here you can set the 'header', the emails 'from' and 'to', the 'subject' and define a 'template' to the e-mail. The MimeMessageHelper class is to create the message.

  • MimeMessagePreparator interface: It is the callback interface for the preparation of JavaMail MIME messages.
  • MimeMessageHelper class: It is the helper class for creating a MIME message. It offers support for inline elements such as images, typical mail attachments and HTML text content.

Below a simple example to create the message using the preparator and helper.

MimeMessagePreparator preparator = new MimeMessagePreparator() {
  public void prepare(MimeMessage mimeMessage) throws Exception {
    MimeMessageHelper msg = new MimeMessageHelper(mimeMessage);
    msg.setTo("to@test.com");
    msg.setSubject("subject");
    msg.setFrom("from@test.com");
    msg.setText("body", true); // body is assumed to be HTML
  }
};

Now, an example using a template.

MimeMessagePreparator preparator = new MimeMessagePreparator(){
  public void prepare(MimeMessage mimeMessage) throws Exception {
  MimeMessageHelper message=new MimeMessageHelper(mimeMessage);
  message.setTo("to@test.com");
  message.setFrom("from@test.com");
  message.setSubject("subject");
  Map<String,Object> model=new HashMap<String,Object>();
  model.put("inviter",inviter);
  model.put("randomkey",randomkey);
  model.put("email",email);
  Template textTemplate=configurer.getConfiguration().getTemplate(template);
  final StringWriter textWriter=new StringWriter();
  textTemplate.process(model,textWriter);
  message.setText(textWriter.toString(),true);
}

Good examples you can see here [1] [2].

JavaMail

Now you have the email (preparator) that you did before. The next step is to send it. For this, JavaMail API helps you.

At this moment you should set the SMTP to deliver the email, the Port, the MIME that you have done.

try {
  JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
  mailSender.setHost(smtpHost);
  mailSender.setPort(smtpPort);
  mailSender.setUsername(smtpUsername);
  mailSender.setPassword(smtpPassword);
  mailSender.send(preparator);
} catch (MailException ex) {
  logger.error("Failed to send email. ");
}

Conclusion

I did this post to give a very short view of the e-mail to know where you should seek about the e-mail related to your feature.

If you already have the functionality to implement to do go to the examples and identify directly your necessities. If you are just studying you can go to the tutorial and do a complete example.

References