SSL-based javamail
Recently, a project needs to support SSL-based javamail to send and receive emails. After some investigation, the javamail method using SSL is summarized as follows.
Javamail providers lack support for SSL connections. Therefore, JSSE APIs must be used to support SSL connections. The following describes how to use JSSE APIs to connect mail storage providers such as POP3, IMAP, and nntp.
The following code must be run in j2se1.4. X or later.
First, you need to register the JSSE security provider to the current virtual machine environment. There are two methods:
1. Modify the Java local security file
<Java_home>/JRE/lib/security/Java. Security
2. dynamically add security provider
Then, use the SSL socket factory of JSSE to replace the default socket factory. The alternative is to set some default attributes of javamail to achieve this.
Mail. <protocol>. socketfactory. Class
Mail. <protocol>. socketfactory. Fallback
Mail. <protocol>. socketfactory. Port
Mail. <protocol>. Timeout
The following code replaces the socket factory of different protocols.
If we want javamail to only process SSL connections and do not process non-SSL connections, we 'd better set fallback to false.
Security. addprovider (New com.sun.net. SSL. Internal. SSL. provider ());
Final string ssl_factory = "javax.net. SSL. sslsocketfactory ";
Properties props = system. getproperties ();
// IMAP provider
Props. setproperty ("mail. imap. socketfactory. Class", ssl_factory );
// POP3 provider
Props. setproperty ("mail. pop3.socketfactory. Class", ssl_factory );
// NNTP provider (if any)
// Props. setproperty ("mail. nntp. socketfactory. Class", ssl_factory );
// IMAP provider
Props. setproperty ("mail. imap. socketfactory. Fallback", "false ");
// POP3 provider
Props. setproperty ("mail. pop3.socketfactory. Fallback", "false ");
// NNTP provider (if any)
// Props. setproperty ("mail. nntp. socketfactory. Fallback", "false ");
Next, we need to use the port corresponding to the SSL protocol to change the default port. This Port varies according to the settings of the mail server. The following code writes the General SSL default port.
// IMAP provider
Props. setproperty ("mail. imap. Port", "993 ");
Props. setproperty ("mail. imap. socketfactory. Port", "993 ");
// POP3 provider
Props. setproperty ("mail. pop3.port", "995 ");
Props. setproperty ("mail. pop3.socketfactory. Port", "995 ");
// NNTP provider (if any)
// Props. setproperty ("mail. pop3.port", "563 ");
// Props. setproperty ("mail. pop3.socketfactory. Port", "563 ");
After setting all the attributes, we can use these attributes to create the session. The subsequent steps are exactly the same as the general javamail processing.
Session session = session. getinstance (props ); For more information about the topic reference, see
Java tip 115: Secure javamail with JSSE
Use javamail to receive/send Gmail mail (SSL)
Javamail: Send mail via SMTP and SSL