Search code examples
smtpjakarta-mailmassmailmail-server

Continuous email server Connection using JAVA Mail API


We are intended to develop a service, which always stay connected to email server, so that whenever a user triggers a mail, it will sent by using the connect instead of getting a new connection and sending the mail. Is is possible that we always stay connection to email server using JAVA Mail API??. kindly help me in this.


Solution

  • When you connect to SMTP server (also when using javax.mail API), you use a socket connection (see the src of SMTPTransport and Transport classes). Sockets let you connect to a remote server and that connection remains open until explicitly closed. This means that theoreticaly you could create a connection and them reuse it.

    However, many SMTP servers are pretty evil and will kill the connection if you are using it "too slow" or if you try to resuse your SMTP session to often. (I looked up postfix settings for you.)

    The Java Mail API allows you to create the connection and close it whenever you want to. Smth. like this:

            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.sendMessage(msg, addressArray);
            // you can do transport.close(); later
    

    However, because of the fact how the SMTP servers are, you can't just execute connect() once and forget it. At most, what you can do, is properly handle forced disconnects by reconnecting again. There is a notification mechanism in the Java Mail API to do that (take a look at the usage of the notifyConnectionListeners method)