JavaMail

Send emails in Java

Today we will discuss how to send emails from your Java app. In general, you have two main options: either use the native built-in functionality or try some external packages. Java provides a quite comprehensive email package. Let’s start with learning how to use it and then have a quick look at other available options (there are not that many of them, indeed). 

What is JavaMail

JavaMail is an official Java API for sending and receiving emails. Starting from July 2019, JavaMail is known as Jakarta Mail. Oracle transferred the rights for Java EE to the Eclipse Foundation, and now the software evolves under the Jakarta EE brand. The official documentation for Jakarta Mail API can be now found here.

In fact, only the project name changed with the Jakarta Mail release. Let’s see how to install it first. The mail package is already included in Jakarta EE and the Java EE platforms.

To download the latest version, go to the Jakarta Mail Implementation page on GitHub. You will need jakarta.mail.jar file: insert it in your CLASSPATH environment then. Alternatively, you can add it with Maven dependencies as follows: 

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

The mail system in Java is built with classes provided by Jakarta Mail API. You will find the detailed descriptions in the official documentation, while in this tutorial we will refer to the main points, which allow us to:

  • add email headers
  • create plain text and HTML messages
  • embed images
  • attach files
  • send messages via SMTP using password authentication

How to build a simple email 

To create a simple mail, we need to import the necessary classes:

  • javax.mail.Message – an abstract class, creates a message 
    • javax.mail.internet.MimeMessage – its sub-class
  • javax.mail.MessagingException – notifies about possible errors
  • javax.mail.PasswordAuthentication – requires password authentication for an SMTP server
  • javax.mail.Session – joins all the properties
  • javax.mail.Transport – sends message
  • javax.mail.internet.InternetAddress – to add email addresses

Then we need to specify the sending server in properties and set message parameters as follows:

package com.example.smtp;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

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 = "username@example.com";
      final String password = "yourpassword";

      // Paste host address 
      String host = "smtp.example.com";

      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");// use the port appropriate for your host 

      // 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("How to send a simple email in Java");
 
    // Put the content of your message
    message.setText("Hi there, this is my first message sent in Java");

    // Send message
    Transport.send(message);

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

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

Here is how this message should look in your test email inbox:

Send emails in Java

Let’s add HTML content

To build a simple template with text formatting, links, or images, we will use HTML. For this purpose, we will use SendHTMLEmail class (unlike SendEmail for a simple message in our previous example) and set MimeMessage.setContent(Object, String):

package com.example.smtp;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

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

      String from = "yourmail@example.com";
      final String username = "yourusername";
      final String password = "yourpassword"

      String host = "smtp.example.com";

      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("newHTML message");

        message.setContent(
              "<h1>This is header</h1>"
,
             "text/html");

       // Send message
       Transport.send(message);

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

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

Here is how the result should look in your test email service:

Send emails in Java with HTML

How to attach files

You can attach files with the attach file method specified in the MimeBodyPart as follows: 

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); }

Other ways to send emails in Java 

Above, we have gone through the main capabilities of the native Java email functionality. What other options can you consider?

The most popular alternatives are:

  • the Spring Framework’s email library 
  • Apache Common Emails
  • Simple Java Mail library

It is worth mentioning that all of them are built on top of the JavaMail API. 

This article on sending emails in Java was originally published on the Mailtrap blog.

Previous
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago