January 21, 2020

Java Mail Sent Over TLS

Blogger

Abstract

The purpose of this blog is to demonstrate how to use Java Mail to send an email using an SMTP server with a TLS connection.

Disclaimer

This post is solely informative. Critically think before using any information presented. Learn from it but ultimately make your own decisions at your own risk.

Requirements

I did all of the work for this post using the following major technologies. You may be able to do the same thing with different technologies or versions, but no guarantees.

  • NetBeans 11.2
  • Maven 3.3.9 (bundled with NetBeans)
  • Java 11 (zulu11.35.15-ca-jdk11.0.5-win_x64)
<dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4</version>
  <scope>test</scope>
</dependency>

Download

Visit my GitHub page https://github.com/mjremijan to see all of my open source projects. The code for this post is located at https://github.com/mjremijan/thoth-email in the thoth-email-via-tls module.

Properties

This example uses an smtp-tls-outlook.properties file to hold the SMTP server information. I used my personal Outlook account for testing, hence the use of the word outlook in the name of the properties file. What’s important are the contents of the file, shown in Listing 1.

Listing 1 - Properties file

# This is the name of the SMTP host machine.
host=

# This is the port number of the SMTP host machine.
# The same host may support both SSL and TLS but on
# different ports. So make sure you get the TLS port.
port=

# This is what you use in the “username” field when
# you login. Typically this is the same as your email
# address, but this isn’t always the case.
username=

# This is what you use in the “password” field when
# you login. This value is CLEAR TEXT, so keep this
# properties file safe.
password=

# This is the email address you want for the
# email’s FROM field. Enter the value using
# the format shown below. Typically this is
# just your email address for the account.
from=FIRSTNAME LASTNAME <ADDRESS@EMAIL.COM>

# This is the email address you want for the
# email’s REPLY_TO field. Enter the value using
# the format shown below. Typically this is
# just your email address for the account. Also
# typically this is the same as `from` above.
# But be warned, if an email’s FROM and REPLY_TO 
# are different, that’s may be flagged as spam
# and never be delivered. So keep `from` and
# `reply` the same for initial testing
reply=FIRSTNAME LASTNAME <ADDRESS@EMAIL.COM>

# This is the email address you want to send
# the email to. For testing, it’s a good idea
# to send it to yourself first.
to=FIRSTNAME LASTNAME <ADDRESS@EMAIL.COM>

Now that you have a properties file, next let’s take a look at the code.

Code

This is a JUnit test demonstrating how to use Java Mail to send an email using an SMTP server with a TLS connection. Listing 2 shows the code.

NOTE For initial testing, always check your SPAM folder. A rule can always be added to deliver to your INBOX.

Listing 2 - Java Mail example

package org.thoth.email.via.tls;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class TlsTest {

  public TlsTest() {
  }

  protected String now, hostname;

  protected Properties outlook;

  @BeforeEach
  public void setUp() throws Exception {
    now = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a").format(new Date());
    hostname = InetAddress.getLocalHost().getHostName();
    outlook = new Properties();
    outlook.load(this.getClass().getResourceAsStream("/smtp-tls-outlook.properties"));
  }

  @Test
  public void a_test() throws Exception {

    // Create MimeMultipart
    MimeMultipart content = new MimeMultipart("related");

    // html part
    {
      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText("<html><body>"
        + "<p>Time: "+now+"</p>"
        + "<p>From: "+hostname+"</p>"
        + "</body></html>"
        , "UTF8", "html");
      content.addBodyPart(textPart);
    }

    // properties
    Properties props = new Properties();
    {
      props.setProperty("mail.smtp.auth", "true");
      props.setProperty("mail.smtp.host", outlook.getProperty("host"));
      props.setProperty("mail.smtp.port", outlook.getProperty("port"));
      props.setProperty("mail.smtp.starttls.enable", "true");

    }

    Session smtp = null;
    {
      smtp = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(
              outlook.getProperty("username")
            , outlook.getProperty("password")
          );
        }
      });
      smtp.setDebug(true);
      smtp.setDebugOut(System.out);
    }


    MimeMessage m = new MimeMessage(smtp);
    {
      m.setRecipient(Message.RecipientType.TO, new InternetAddress(outlook.getProperty("to")));
      m.setSubject("thoth-email TLS test " + now);

      InternetAddress from = null;
      {
        from = new InternetAddress(outlook.getProperty("from"));
        from.setPersonal("Thoth Email");
        m.setFrom(from);
      }

      InternetAddress reply = null;
      {
        reply = new InternetAddress(outlook.getProperty("reply"));
        m.setReplyTo(new InternetAddress[] {reply});
      }


      m.setContent(content);
    }

    Transport.send(m);
  }

}

Summary

The code for sending mail is not very hard. Successfully receiving an email without being flagged as SPAM is another matter. But if you follow this example, use a valid account, and don’t overuse it, you should be OK. This blog shows how to use Java Mail to send an email using an SMTP server with a TLS connection.