I have a spring-stand alone application which uses simple spring email code as below , the to
and the message
is constructed using the values iter
IMHO, the process of sending mail itself can be improved, because currently, you open an new connection to mail server per message. You could improve it by using batched sending.
Spring MailSender
interface natively supports sending of an array of messages instead of a single one, so you do not have do explicitely deal with JavaMail Session. You could simply modifiy the class actually sending the mail that way
int batchSize = 16; // for example, adjust it to you needs
MimeMessage[] messages = new MimeMessage[batchSize];
int messageIndex = 0;
public void sendMail(String msgFrom, String body) {
// prepare MimeMessage
messages[messageIndex++] = email;
if (messagesIndex == batchSize) {
mailSender.send(messages);
messageIndex = 0;
}
public void sendLastMails() {
if (messageIndex > 0) {
MimeMessage[] lastMessages = new MimeMessage[messageIndex];
for (int i =0; i<messageIndex; i++) {
lastMessages[i] = messages[i];
}
mailSender.send(lastMessages);
}
Edit:
The sendLastMails
method may be called in several places. First, it must be called in the destroy method of a singleton bean to make sure no messages are forgotten when application closes. If the class sending mail is a singleton bean, it is enough to declare that the destroy method for the bean is sendLastMail
, or calls it.
Then depending on you own business rules, it may be called after a batch of mails have been sent. Typical usage : in you example, you have testMap
. You should rewrite it that way :
for (Map.Entry<String, List<values>> entry : testMap
.entrySet()) {
...
mail.sendMail( msgFrom,body); // call my sendMail function in another class
}
mail.sendLastMails();
Now it is up to you to see if this improvement is enough or if you should outsource.
Basically the answer is to not do this yourself.
Here is a very detailed reason why not: How to send 100,000 emails weekly?
You can enclose sendMail into separate Runnable class and put tasks into ExecutorService ( or use @Async above sendMail method, but this is harded to configure - just my opinion ).