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
JavaMail now supports the use of SSL/TLS to establish secure connections to access mail servers. In order to simplify secure access, two methods of enabling SSL secure connection are provided: Configure connection properties.
The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with the Java SE platform and is also included in the Java EE platform.
A: Yes. The JavaMail API implementation is completely free and open source and you can include it in your product. This release includes IMAP, POP3, and SMTP providers as well.
javax.mail. Class Session. java.lang.Object javax.mail.Session public final class Session extends java.lang.Object. The Session class represents a mail session and is not subclassed. It collects together properties and defaults used by the mail API's.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With