Tutorial: How to send email from a Java Application – via a Server requiring Authentication

In the previous tutorial we walked through how to send email from a Java Application. This tutorial extends off that and explains how to send email from a SMTP server that requires  basic User Authentication in the form of a user name and password.  This is performed by use of the Authenticator object.


This tutorial builds off of the previous example and as such you will need to review that tutorial to understand the requirements necessary to utilize the JavaMail API.

How to send an email from SMTP Server requiring User Name/Password Authentication

To get started lets build off of our MailUtil class we have already created by copying the class and refactoring it to BasicAuthMailUtil. For those who don’t know what refactoring is it means to rename the class.

After we have refactored the class our first step is to create our Authenticator object. Now we could do this by creating a separate class or creating an internal class. For our purposes we will create an internal class. To create an internal class you simply declare a class inside the class declaration of another class. We would do this by placing our BasicSMPTAuthenticator class stub before the closing } of our BasicAuthMailUtil class.

public class BasicAuthMailUtil {
  /* existing code */

  private class BasicSMTPAuthenticator
        extends javax.mail.Authenticator



For our Authenticator to function we need to implement the getPasswordAuthentication method which will return to the caller a PasswordAuthentication object with the desired username and password

public PasswordAuthentication getPasswordAuthentication()
  return new PasswordAuthentication( AUTH_USER, AUTH_PSWD );

You could replace the AUTH_USER and AUTH_PSWD values directly with the user and password information for the server or define them as variables of the BasicAuthMailUtil Class.

private static String AUTH_USER = "USER NAME";
private static String AUTH_PSWD = "PASSWORD";

Now that our Authenticator is created the last step is to initialize the session with our Authenticator. Therefore we will modify:

Session sess = Session.getInstance(props);

with the following which instantiates our Authenticator then obtains the Mail Session Instance based on the properties and Authenticator.

Authenticator auth = new BasicSMTPAuthenticator();
Session sess = Session.getDefaultInstance( props, auth );

Congratulations you now have a utility class that can send emails from a SMTP Server that requires user name and password authentication.


// Java //

Comments & Questions

Add Your Comment