Wednesday, December 17, 2014

Leverage Spring JavaMailSender's batch send method and gain performance when sending series of emails...

I have recently experienced a performance issue in a module that is coded to send email notifications to multiple recipients using Spring Java Mail support. The email text for each recipient was different and hence it was initially coded to loop through all recipients, prepare MimeMessage with the help of an anonymous inner class of MimeMessagePreparator for each recipient, and call JavaMailSender's send(MimeMessagePreparator mimeMessagePreparator) method. For every message the send method was taking about 20 secs or so for the call to finish. When there about 20 recipients, there were 20 such calls to this method and the delay was noticeable in minutes.

While reading through the Javadoc of Spring classes, I found that there is another send method in JavaMailSender class which takes an array of MimeMessages as an argument and sends mail in batch mode. I used this method instead and prepared an array of MimeMessages one per each recipient using just the MimeMessageHelper. This improved the performance and for 20 recipients which is 20 emails anyway, it only took about 20 seconds.

Under the covers this method could be using the same mail session to send all MimeMessages in batch mode.

2 comments:

  1. can you please share your code on how you implemented it

    ReplyDelete
    Replies
    1. It's been awhile, I wrote that code for the company I was working for at that time. Unfortunately, I don't have any code snippets to share. Hope I had given enough details in this post.

      Delete