Guide to Send Emails in Java

Java has been ranking as one of the most popular web programming languages for many years. In this tutorial on sending emails in Java, which was originally published on the Mailtrap blog, we will demonstrate how to build HTML emails with images and attachments and send them using an SMTP server.

The main option is to use a Java API for sending and receiving emails via SMTP, POP3, and IMAP. It is implemented as an optional package compatible with any operating system. At the same time, Jakarta Mail is supplied as a part of Jakarta EE and Java EE platforms. In the earlier releases, the mail package was titled “JavaMail API”. However, since July 2019, the Java software has been further developed by the Eclipse Foundation. This is why the email package also got the new name. All main classes and properties are the same for both JavaMail and Jakarta Mail.

In this article, we will describe the main email package properties and will show how to send different types of messages.

Getting Started with Jakarta Mail (JavaMail)

To start working with Jakarta Mail, first of all, you should insert jakarta.mail.jar file into your CLASSPATH environment. You can download it from the (Jakarta Mail project page on GitHub)[https://javaee.github.io/javamail/].

Besides, you can find Jakarta Mail jar files in the Maven repository and add them to your environment with Maven dependencies:

<dependencies>
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>jakarta.mail</artifactId>
        <version>1.6.4</version>
    </dependency>
</dependencies>

Please note that if you use JDK 1.5 or older versions, you will also need an implementation of the JavaBeans Activation Framework.

import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;

Let’s focus on the main steps for preparing HTML email and sending it via an external SMTP server.

Jakarta Mail Classes and Syntax

Before we move to code, let’s review core classes and properties, which are most frequently used for building and sending messages with Jakarta Mail.

Session Class (javax.mail.Session) is the primary one connecting all the properties and defaults. The following methods are used to get the session object:

  • getDefaultInstance() returns the default session

  • public static Session getDefaultInstance/(Properties props)

  • public static Session getDefaultInstance(Properties props, Authenticator auth)

  • getInstance() returns the new session.

  • public static Session getInstance(Properties props)

  • public static Session getInstance(Properties props, Authenticator auth)

Message class (javax.mail.Message) is an abstract class for actually building an email message. We will mostly use its Mime Message (javax.mail.internet.MimeMessage) subclass and its main methods:

  • setFrom(Address[] addresses) sets the “From” header field.

  • public void addFrom(Address[] addresses)

  • addRecipients(Message.RecipientType type, String addresses) adds the given address to the recipient type.

  • public void addRecipient(Message.RecipientType type, Address[] addresses)

  • Message.RecipientType.TO “To”

  • Message.RecipientType.CC “Cc”

  • Message.RecipientType.BCC “Bcc”

  • MimeMessage.RecipientType.NEWSGROUPS “Newsgroups”

  • setSubject(String subject) sets the subject header field.

  • public void setSubject(String subject)

  • setText(String textmessage) sets the text as the message content using text/plain MIME type.

  • public void setText(String textmessage)

  • setContent(Object o, String type) sets this message’s content.

  • public void setContent(Object o, String type)

To send emails via an external SMTP server, use com.sun.mail.smtp package: it is an SMTP protocol provider for the JavaMail API that provides access to an SMTP server.

The main properties are:

  • mail.smtp.user, default username for SMTP.

  • mail.smtp.host, the SMTP server to connect to.

  • mail.smtp.port, the SMTP server port to connect to, if the connect() method doesn’t explicitly specify one. Defaults to 25.

To enable SMTP authentication, set the mail.smtp.auth property or provide the SMTP Transport with a username and password when connecting to the SMTP server.

We will show how to implement it later, when demonstrating code examples.

SMTPMessage class is a specialization of the MimeMessage class for specifying SMTP options and parameters. Simply use this class instead of MimeMessage and set SMTP options using the methods on this class.

  • public SMTPMessage(Session session)

  • Transport ( javax.mail.Transport) is an abstract class for sending messages.

  • Transport.send(message)

To view all classes and their methods, see this section of the Jakarta Mail documentation.

Sending Emails in Java via SMTP

Let’s now review how to implement classes and methods described above and write some Java code to send an email via an external SMTP server.

First of all, we need to define who sends what to whom. So, use the SendEmail public class and set “from” and “to” email addresses and add the subject. With javax.mail.PasswordAuthentication class we will be able to require password authentication to send a message via SMTP server.

In the properties method, we will add the necessary SMTP settings and then create a mail Session object. Afterward, you can create a Message using the MimeMessage.

Finally, send your message with the Transport object.

Don’t forget to add Exceptions. This class enables you to get details on possible errors along with an understanding of how to debug them. The main one is MessagingException. It can be used within javax.mail, javax.mail.internet, and javax.mail.search packages. For example, AddressException for javax.mail.internet will be thrown if you offered a wrongly formatted address.

We will return to debugging a bit later in this post.

How to test emails in Java?

For testing email sending from Java, we will use Mailtrap, an online tool, which helps test, review, and analyze emails sent from dev, QA, or staging environments, without the risk of spamming your customers or colleagues. Once you have tested and verified that everything works properly, change settings for the server you use in production.

Input:

package com.example.smtp;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmail {
    public static void main(String[] args) {
        // Put recipient’s address
        String to = "test@example.com";

        // Put sender’s address
        String from = "from@example.com";
        final String username = "1a2b3c4d5e6f7g";//username generated by Mailtrap
        final String password = "1a2b3c4d5e6f7g";//password generated by Mailtrap

        // Paste host address from the SMTP settings tab in your Mailtrap Inbox
        String host = "smtp.mailtrap.io";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");//it’s optional in Mailtrap
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "2525");// use one of the options in the SMTP settings tab in your Mailtrap Inbox

        // Get the Session object.
        Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

        try {
            // Create a default MimeMessage object.
            Message message = new MimeMessage(session);

            // Set From: header field
            message.setFrom(new InternetAddress(from));

            // Set To: header field
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));

            // Set Subject: header field
            message.setSubject("My first message with JavaMail");

            // Put the content of your message
            message.setText("Hi there, this is my first message sent with JavaMail");

            // Send message
            Transport.send(message);

            System.out.println("Sent message successfully....");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Output:

Sending HTML Email

To send an HTML email, you should perform the same steps as for sending a simple text message, with only SendHTMLEmail class instead of just SendEmail. Also, you need to set content to the MimeMessage.setContent(Object, String) and indicate text/html type.

Input:

package com.example.smtp;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendHTMLEmail {
    public static void main(String[] args) {
        String to = "johndoe@gmail.com";

        String from = "yourmail@example.com";
        final String username = "1a2b3c4d5e6f7g";//generated by Mailtrap
        final String password = "1a2b3c4d5e6f7g";//generated by Mailtrap

        String host = "smtp.mailtrap.io";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "2525");

        // Get the Session object.
        Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

        try {
            // Create a default MimeMessage object.
            Message message = new MimeMessage(session);

            message.setFrom(new InternetAddress(from));

            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));

            message.setSubject("My HTML message");

            // Put your HTML content using HTML markup
            message.setContent(
                "<div><span style=\"color:#57aaca;\">c</span><span style=\"color:#57aec5;\">o</span><span style=\"color:#57b2c0;\">l</span><span style=\"color:#57b6ba;\">o</span><span style=\"color:#57bbb5;\">r</span><span style=\"color:#56bfb0;\">f</span><span style=\"color:#56c3ab;\">u</span><span style=\"color:#56c7a5;\">l</span><span style=\"color:#56cba0;\"> </span><span style=\"color:#5ec3ab;\">m</span><span style=\"color:#65bbb6;\">e</span><span style=\"color:#6db3c1;\">s</span><span style=\"color:#75accd;\">s</span><span style=\"color:#7da4d8;\">a</span><span style=\"color:#849ce3;\">g</span><span style=\"color:#8c94ee;\">e</span></div>", "text/html");

            // Send message
            Transport.send(message);

            System.out.println("Sent message successfully....");

        } catch (MessagingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

Output:

In Mailtrap, you can also check the raw data of your message as well as its HTML source on separate tabs.

If you would like your message to contain both HTML and plain text, you need to build it using a MimeMultipart(“alternative”) object. You should create two different parts manually and insert them separately: text/plain body part as the first part in the multipart the text/html body part as the second one.

HTML Email with Images in Java

To add an image to your HTML emails in Jakarta Mail, you can choose any of three regular options: CID, base64 image, or linked image.

To embed a CID image, you need to create a MIME multipart/related message:

Multipart multipart = new MimeMultipart("related");

MimeBodyPart htmlPart = new MimeBodyPart();
//add reference to your image to the HTML body <img src="cid:some-image-cid" alt="img" />
htmlPart.setText(messageBody, "utf-8", "html");
multipart.addBodyPart(htmlPart);

MimeBodyPart imgPart = new MimeBodyPart();
// imageFile is the file containing the image
imgPart.attachFile(imageFile);
// or, if the image is in a byte array in memory, use
// imgPart.setDataHandler(new DataHandler(
// new ByteArrayDataSource(bytes, "image/whatever")));

imgPart.setContentID("<some-image-cid>");
multipart.addBodyPart(imgPart);

message.setContent(multipart);

For a base64, or inlined image, include the encoded image data in the HTML body:

<img src="data:image/jpeg;base64,base64-encoded-data-here" />

But remember that each Base64 digit represents 6 bits of data, so your actual image code will be pretty long. Besides, it affects the overall size of the HTML message, so it’s better not to inline large images.

The simplest way to add an image is just linking to the image hosted on some external server. Refer to your image as a link in the HTML body with an “img” tag:

<img src="https://blog.mailtrap.io/wp-content/uploads/2018/11/blog-illustration-email-embedding-images.png" alt="img" />

Sending an Email with Attachments

To attach any type of files to your message, you need to build a MIME multipart message and indicate the attachFile method in the MimeBodyPart.

public void attachFile(File file, Multipart multipart, MimeBodyPart messageBodyPart) { 
    DataSource source = new FileDataSource(file);

    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(file.getName());

    multipart.addBodyPart(messageBodyPart); 
}

Debug Jakarta Mail

Debugging plays a critical role in testing of email sending. In Jakarta Mail it’s pretty straightforward. Set debug to true in the properties of your email code:

props.put("mail.debug", "true");

As a result, you will get a step by step description of how your code is executed. If any problem with sending your message appears, you will instantly understand what happened and at which stage.

Here is how our HTML message debug output looks:

DEBUG: Jakarta Mail version 1.6.4
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: need username and password for authentication
DEBUG SMTP: protocolConnect returning false, host=smtp.mailtrap.io, user=diana, password=<null>
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.mailtrap.io", port 2525, isSSL false
220 mailtrap.io ESMTP ready
DEBUG SMTP: connected to host "smtp.mailtrap.io", port: 2525
EHLO DESKTOP-NLP1GG8
250-mailtrap.io
250-SIZE 5242880
250-PIPELINING
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-AUTH PLAIN LOGIN CRAM-MD5
250 STARTTLS
DEBUG SMTP: Found extension "SIZE", arg "5242880"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN CRAM-MD5"
DEBUG SMTP: Found extension "STARTTLS", arg ""
STARTTLS
220 2.0.0 Start TLS
EHLO DESKTOP-NLP1GG8
250-mailtrap.io
250-SIZE 5242880
250-PIPELINING
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250 AUTH PLAIN LOGIN CRAM-MD5
DEBUG SMTP: Found extension "SIZE", arg "5242880"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN CRAM-MD5"
DEBUG SMTP: protocolConnect login, host=smtp.mailtrap.io, user=1e2b3c4d5e6f7g, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2 
DEBUG SMTP: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<yourmail@example.com>
250 2.1.0 Ok
RCPT TO:<johndoe@gmail.com>
250 2.1.0 Ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   johndoe@gmail.com
DATA
354 Go ahead
Date: Tue, 30 Jul 2019 17:19:31 +0200 (EET)
From: yourmail@example.com
To: johndoe@gmail.com
Message-ID: <20132171.0.1548256771226@DESKTOP-NLP1GG8>
Subject: My HTML message
MIME-Version: 1.0
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

<div><span style="color:#57aaca;">c</span><span style="color:#57aec5;">o</span><span style="color:#57b2c0;">l</span><span style="color:#57b6ba;">o</span><span style="color:#57bbb5;">r</span><span style="color:#56bfb0;">f</span><span style="color:#56c3ab;">u</span><span style="color:#56c7a5;">l</span><span style="color:#56cba0;"> </span><span style="color:#5ec3ab;">m</span><span style="color:#65bbb6;">e</span><span style="color:#6db3c1;">s</span><span style="color:#75accd;">s</span><span style="color:#7da4d8;">a</span><span style="color:#849ce3;">g</span><span style="color:#8c94ee;">e</span></div>
.
250 2.0.0 Ok: queued
DEBUG SMTP: message successfully delivered to mail server
QUIT
221 2.0.0 Bye
Sent message successfully....

Need More Options?

In this post, we have guided you through the main Jakarta Mail use cases and options. Should you experience any difficulties with installing, implementing, or using this package, refer to the Jakarta Mail FAQ.

Indeed, constructing transactional emails to send from your Java app with Jakarta Mail API takes time. Alternatively, you can consider options for simplified email sending in Java. For example, the Spring Framework or Apache Common Emails are quite popular, while the Play Framework offers a plugin for sending emails. Simple Java Mail is one of the simplest libraries ever – in fact, it is a wrapper around JavaMail API.

How do I receive mail using POP3?

In this example you will learn how to receive email using POP3. We are going to connect to Gmail server and read the messages in the INBOX folder. There are some steps that you need to do to download this email. Here are the steps:

  1. Setup properties for the mail session.
  2. Creates a javax.mail.Authenticator object.
  3. Creating mail session.
  4. Get the POP3 store provider and connect to the store.
  5. Get folder and open the INBOX folder in the store.
  6. Retrieve the messages from the folder.
  7. Close folder and close store.

These steps can be written as the following code snippet:

package org.kodejava.mail;

import javax.mail.*;
import java.util.Properties;

public class ReadEmail {
    public static final String USERNAME = "kodejava";
    public static final String PASSWORD = "password";

    public static void main(String[] args) throws Exception {
        // 1. Setup properties for the mail session.
        Properties props = new Properties();
        props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.pop3.socketFactory.fallback", "false");
        props.put("mail.pop3.socketFactory.port", "995");
        props.put("mail.pop3.port", "995");
        props.put("mail.pop3.host", "pop.gmail.com");
        props.put("mail.pop3.user", ReadEmail.USERNAME);
        props.put("mail.store.protocol", "pop3");
        props.put("mail.pop3.ssl.protocols", "TLSv1.2");

        // 2. Creates a javax.mail.Authenticator object.
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(ReadEmail.USERNAME, ReadEmail.PASSWORD);
            }
        };

        // 3. Creating mail session.
        Session session = Session.getDefaultInstance(props, auth);

        // 4. Get the POP3 store provider and connect to the store.
        Store store = session.getStore("pop3");
        store.connect("pop.gmail.com", ReadEmail.USERNAME, ReadEmail.PASSWORD);

        // 5. Get folder and open the INBOX folder in the store.
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);

        // 6. Retrieve the messages from the folder.
        Message[] messages = inbox.getMessages();
        for (Message message : messages) {
            message.writeTo(System.out);
        }

        // 7. Close folder and close store.
        inbox.close(false);
        store.close();
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create a simple mail client program in Swing?

The code snippet below show you how to create a simple Java Swing application that can be used to send an e-mail. The program allows user to supply the from email address, to email address, the subject and the message of the email. User need to select the available SMTP server to connect to and provide the username and password for authentication to the mail server.

Here is the user interface of this simple email client:

Simple E-mail Client

Simple E-mail Client

The main routine for sending the email is in the SendEmailActionListener class, which is an implementation of an ActionListener interface that will handle email sending process when Send E-mail button is pressed.

package org.kodejava.mail;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Properties;

public class SendEmailClient extends JFrame {
    private final JTextField fromField = new JTextField();
    private final JTextField toField = new JTextField();
    private final JTextField subjectField = new JTextField();
    private final JComboBox<String> mailSmtpHostComboBox = new JComboBox<>();
    private final JTextField usernameField = new JTextField();
    private final JPasswordField passwordField = new JPasswordField();
    private final JTextArea contentTextArea = new JTextArea();

    private SendEmailClient() {
        InitializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SendEmailClient client = new SendEmailClient();
            client.setVisible(true);
        });
    }

    private void InitializeUI() {
        setTitle("Send E-mail Client");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(new Dimension(500, 500));

        getContentPane().setLayout(new BorderLayout());

        // Header Panel
        JPanel headerPanel = new JPanel();
        headerPanel.setLayout(new GridLayout(6, 2));
        headerPanel.add(new JLabel("From:"));
        headerPanel.add(fromField);

        headerPanel.add(new JLabel("To:"));
        headerPanel.add(toField);

        headerPanel.add(new JLabel("Subject:"));
        headerPanel.add(subjectField);

        headerPanel.add(new JLabel("SMTP Server:"));
        headerPanel.add(mailSmtpHostComboBox);
        mailSmtpHostComboBox.addItem("smtp.gmail.com");

        headerPanel.add(new JLabel("Username:"));
        headerPanel.add(usernameField);

        headerPanel.add(new JLabel("Password:"));
        headerPanel.add(passwordField);

        // Body Panel
        JPanel bodyPanel = new JPanel();
        bodyPanel.setLayout(new BorderLayout());
        bodyPanel.add(new JLabel("Message:"), BorderLayout.NORTH);
        bodyPanel.add(contentTextArea, BorderLayout.CENTER);

        JPanel footerPanel = new JPanel();
        footerPanel.setLayout(new BorderLayout());
        JButton sendMailButton = new JButton("Send E-mail");
        sendMailButton.addActionListener(new SendEmailActionListener());

        footerPanel.add(sendMailButton, BorderLayout.SOUTH);

        getContentPane().add(headerPanel, BorderLayout.NORTH);
        getContentPane().add(bodyPanel, BorderLayout.CENTER);
        getContentPane().add(footerPanel, BorderLayout.SOUTH);
    }

    private class SendEmailActionListener implements ActionListener {
        SendEmailActionListener() {
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Properties props = new Properties();
            props.put("mail.smtp.host", mailSmtpHostComboBox.getSelectedItem());
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.ssl.protocols", "TLSv1.2");

            Session session = Session.getDefaultInstance(props);
            try {
                InternetAddress fromAddress = new InternetAddress(fromField.getText());
                InternetAddress toAddress = new InternetAddress(toField.getText());

                Message message = new MimeMessage(session);
                message.setFrom(fromAddress);
                message.setRecipient(Message.RecipientType.TO, toAddress);
                message.setSubject(subjectField.getText());
                message.setText(contentTextArea.getText());

                Transport.send(message, usernameField.getText(),
                        new String(passwordField.getPassword()));
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

What are the system properties used for sending email?

Here are a list of system properties that can be used to send an e-mail using the JavaMail API.

Property Default Value Description
mail.host Define the host name of the mail server.
mail.smtp.host Define the host name of the SMTP server; this will overrides the mail.host for SMTP connections only.
mail._protocol_.host Define the host name of the specified protocol (POP, IMAP); this will overrides the mail.host.
mail.user Define the default username sent to all mail servers.
mail._protocol_.user Define the default username for the specified protocol; this will overrides the mail.user for the specified protocol.
mail.smtp.port 25 Define the SMTP port on which the SMTP server is listening.
mail._protocol_.port Default port for the corresponding protocol Define the port on which the servers for the specified protocol is listening.
mail.smtp.starttls.enable Upgrade the regular SMTP connection on the usual port to an encrypted (TLS or SSL) connection.
mail.smtp.connectiontimeout Infinite Define the number of milliseconds to wait for a connection timeout.
mail.debug false Define parameter for disabling or enabling information debugging.
mail.from Define the e-mail address to use in the From header.
mail.mime.charset file.encoding Define the default character set used to send messages.
mail.alternates Define other email address for the current that will not to be included when replying to a message.
mail._protocol_.class Define the fully package qualified class name of the provider for the specified protocol.
mail.transport.protocol First transport provider in the configuration file Define default protocol with which to send messages.
mail.transport.protocol.address-type Define the message transport protocol such as SMTP for the specified address type, for example mail.transport.protocol.rfc822.
mail.replayallcc false Put all recipients in the CC list of the reply message instead of the TO field when replying to all.

How do I send an HTML email?

The following code snippets show you how to send an HTML e-mail. We begin by defining the e-mail information such as the from address, to address and the subject. The next step it to create a Properties that will be used to create a mail Session object. Having a Session object we can then create a Message using the MimeMessage.

We use the MimeMessage.setContent(Object, String) to set the html content of the email. Do not forget to set the content type to text/html and also supply the character set, in the example we use charset=utf-8.

package org.kodejava.mail;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendHTMLEmail {
    public static void main(String[] args) {
        String from = "kodejava@gmail.com";
        String to = "kodejava@gmail.org";
        String subject = "Hello";

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        Session session = Session.getDefaultInstance(props);

        try {
            InternetAddress fromAddress = new InternetAddress(from);
            InternetAddress toAddress = new InternetAddress(to);

            Message message = new MimeMessage(session);
            message.setFrom(fromAddress);
            message.setRecipient(Message.RecipientType.TO, toAddress);
            message.setSubject(subject);

            String sb = "<head>" +
                    "<style type=\"text/css\">" +
                    "  .red { color: #f00; }" +
                    "</style>" +
                    "</head>" +
                    "<h1 class=\"red\">" + message.getSubject() + "</h1>" +
                    "<p>" +
                    "Lorem ipsum dolor sit amet, <em>consectetur</em> adipisicing elit, " +
                    "sed do eiusmod tempor incididunt ut labore et dolore magna <strong>" +
                    "aliqua</strong>.</p>";
            message.setContent(sb, "text/html; charset=utf-8");
            message.saveChanges();

            // Send the message to the recipient. You also need to specify the username 
            // and password to authenticate to the mail server.
            Transport.send(message, "kodejava", "password");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central