Sending mail to an SMTP server with authentication using JavaMail
SUMMUS, Written by Kris Hadlock, Published on Friday, July 29th, 2011
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:
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.)
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.
That’s it! When put together, this code successfully sends mail messages to SMTP servers with authentication. A test can be found below.