My application needs to send emails on an ad hoc basis. I'm using javamail's getDefaultSession and getTransport to send the message, and it's all working as expected.
However I've noticed that the send can take a long time - up to seven seconds per send. If I break the steps down, like this:
Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage( msg, addresses )
transport.close();
...I can see that it's the connect() call that takes almost all of the time, each time.
All of the examples I've found do this - get a transport, connect, send, disconnect. But of course they're all single-shot examples, or sending large batches of emails in a single call.
I was thinking I could just leave the connection open, like this:
Transport transport = session.getTransport("smtp");
if (!transport.isConnected())
transport.connect();
transport.sendMessage( msg, addresses )
(There's a variation on that, here: java mail keeping Transport object connected).
I'll have to close it eventually, in a shutdown hook of some kind. And I might have to have a fallback (if the connection has been lost but the transport doesn't realise). But is there any reason not to just leave it open like this during the application lifetime?
Thanks, Alastair
I don't really see any problem in keeping a single SMTP connection open, and the use of Transport Object is recommended for connection reuse (see the JavaMail tutorial).
Additionally, I would recommend you to keep just one smpt connection (through Transport) open at your application, keeping it at a single manager instance (i.e using a singleton pattern), avoiding the eventual cost of keeping a different connection open for every component which needs send a message.