简体   繁体   中英

Reuse connection when sending email with Javamail library

I'm trying to send a lot of email using the JavaMail API and am finding that the slowest part of my code (around 1 second per email) is the following:

long startSendTime = System.currentTimeMillis();
Transport transport = mailSession.getTransport();
transport.connect();
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
long endTime = System.currentTimeMillis();
logger.info("Finished sending message, took: " + (endTime - startSendTime) + "ms");

I am guessing this is because every email requires setting up a TCP connection. Is there a way to have a connection pool for email sending? Are there other libraries that are more performant which I could use?

You have multiple options here depending on the result you are looking for.

With your current implementation, you add additional time for the socket connect / disconnect - this is what a connection pool would solve.

Option 1

With a connection pool, the result is that you grab an already established channel, and your only wait time is for that message to actually be sent.

This gives you the advantage in that you can return a response dependent on whether or not the message was actually sent through the relay successfully - this is still blocking network IO, and probably the longest of the calls.

Option 2

If you do not care about the response message, or can come back for it at a later time - you can optionally add the message to a queue somewhere else, where a separate thread, independent of the users interactions is doing the network IO. This will result in a much faster execution, as you end up with no blocking calls on your UI thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM