Enterprise Java

Java Mail Sent Over TLS

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)
1
2
3
4
5
6
<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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 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

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
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.

Published on Java Code Geeks with permission by Michael Remijan, partner at our JCG program. See the original article here: Java Mail Sent Over TLS

Opinions expressed by Java Code Geeks contributors are their own.

Michael Remijan

Michael Remijan is a System Architect at the Federal Reserve Bank St. Louis. He is co-author of 'EJB 3 In Action Second', an active blogger in the Java EE community, a Java EE Guardian, and JavaOne presenter. He has developed enterprise systems for B2C and B2B commerce, manufacturing, astronomy, agriculture, telecommunications, national defense, healthcare, and financial areas.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button