Many SMTP servers use an authentication system as an extra layer of security in their mail transport. If you need to send email to such a server with JavaMail, the library provides a convenient abstraction of the process. First, create an anonymous inner class that implements javax.mail.Authenticator
and contains the password authentication information:
[gist id=1114931 file=Part_1-Authenticator.java]
Next, create instances of java.util.Properties
and javax.mail.Session
that will be used to build the message transport. The important differences from JavaMail usage here are the extra auth
property and the passing of the authenticator
object to the mail session. (Note that all values of the Properties
instance are strings — this is required by the class. Booleans, integers, et cetera should be passed as strings to this object.)
[gist id=1114931 file=Part_2-Properties_and_Session.java bump=1]
Now that our Session
is prepared, we can send the message as normal. The authentication model is carried within the mail session, so each message can take it in and reuse its information.
[gist id=1114931 file=Part_3-Sending.java bump=2]
That’s it! When put together, this code successfully sends mail messages to SMTP servers with authentication. A test can be found below.
[gist id=1114931 file=JavaMail_SMTP_with_authentication.java bump=3]
Sending mail to an SMTP server with authentication using JavaMail
SUMMUS, Written by Kris Hadlock