How to send emails in Java

For years, Java has held its position as one of the most used web programming languages, and its popularity continues to soar even in early 2023.

Emails also enjoy huge amounts of popularity, given their widespread use, and are a go-to form of communication that all companies leverage to keep their users informed and up-to-date.

In this article, you’ll learn the basics of how to send emails using Java, along with a few other important steps that are often required in the process. Let’s dive in!

The most popular way to send emails using Java

email testing

When it comes to sending emails using Java, the most common solution is Jakarta Mail. This powerful API supports sending and receiving emails through popular protocols like SMTP, POP3, and IMAP and even offers secure authentication options like TLS and SSL.

It’s essential to keep in mind that Jakarta Mail and JavaMail refer to the same thing, and many developers still use the original name.

But regardless of how you call it, the API has been widely adopted for its versatility as it is independent of any platforms or protocols.

You can find it integrated into the Jakarta EE platform or obtain it as an optional package for use with Java SE.

How to send emails in Java using Jakarta Mail?

Learning to send emails with Jakarta Mail is not that much of a challenge – you just need to complete 2 steps.

Step 1. Learn the basics of Jakarta Mail

If you haven’t dealt with Jakarta Mail before, let us introduce you to some fundamentals you need to know to understand the API better, such as the installation process and the classes and methods in Jakarta Mail.

Installation

To start using Jakarta Mail, you have to add the jakarta.mail.jar file to your CLASSPATH environment. You can find the file on the Jakarta Mail’s Github ​​project page or retrieve it from the Maven repository using Maven dependencies:

<dependencies>

<dependency>

<groupId>com.sun.mail</groupId>

<artifactId>jakarta.mail</artifactId>

<version>2.1.1</version>

</dependency>

</dependencies>

 

Note: In some tutorials, you might come across the “javax.mail” instead of the “jakarta.mail” reference in the dependencies. The first just refers to older versions of Jakarta Mail.

Also, depending on when you’re reading this, the version you’re retrieving from the Maven repository may be different — version 2.1.1 is the latest as of mid-February 2023.

Classes and methods

Classes in Jakarta Mail are what you need to use to create and send email messages. Among them, the Message class serves as the foundation.

Message is an abstract class, which means that it requires a subclass to be implemented. And for emails that comply with the standards of RFC822 and MIME, the MimeMessage subclass is used.

A MIME-style email can be filled with various attributes and content via different methods that the MimeMessage subclass provides. These methods allow you to modify different message aspects, such as the “From,” “To,” and “Subject” fields, email body content, and so on.

Step 2. Sending a Simple Jakarta Mail Message (via an SMTP Server)

Now that we’ve covered the basics, it’s time to move on to the actual process of sending a plain-text email using the Jakarta Mail API.

Below is a code example, which you can just copy and paste into your project to easily create an email. Note that there are things you’ll have to change, like the recipient’s address, SMTP server username, password, etc.

Note: The code snippets in this article include SMTP server credentials provided by Mailtrap Email Testing as these snippets are intended for testing/demonstration purposes only and should not deliver emails to recipient inboxes. Please replace these with credentials provided to you by your SMTP server of choice.

package org.example.jakartaemail;

import java.util.Properties;

import jakarta.mail.Message;

import jakarta.mail.MessagingException;

import jakarta.mail.PasswordAuthentication;

import jakarta.mail.Session;

import jakarta.mail.Transport;

import jakarta.mail.internet.InternetAddress;

import jakarta.mail.internet.MimeMessage;

 

public class JakartaEmail {

public static void main(String[] args) {

//provide recipient’s email ID

String to = “jakartato@example.com”;

//provide sender’s email ID

String from = “jakartafrom@example.com”;

//provide Mailtrap’s username

final String username = “a094ccae2cfdb3”;

//provide Mailtrap’s password

final String password = “82a851fcf4aa33”;

//provide Mailtrap’s host address

String host = “smtp.mailtrap.io”;

//configure Mailtrap’s SMTP server details

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”, “587”);

//create the Session object

Session session = Session.getInstance(props,

new jakarta.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);

}

});

try {

//create a MimeMessage object

Message message = new MimeMessage(session);

//set From email field

message.setFrom(new InternetAddress(from));

//set To email field

message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

//set email subject field

message.setSubject(“Here comes Jakarta Mail!”);

//set the content of the email message

message.setText(“Just discovered that Jakarta Mail is fun and easy to use”);

//send the email message

Transport.send(message);

System.out.println(“Email Message Sent Successfully”);

} catch (MessagingException e) {

throw new RuntimeException(e);

}

}

}

 

The code sample above is for sending a plain text email, but you can also send an HTML email via Jakarta Mail API.

To create an HTML email instead of a plain text one, you only have to replace the setText(String text) method with the setContent(Object o, String type) method and specify “text/html” as the second argument.

However, if you want to include both HTML and plain text in your email, you’ll need to use a MimeMultipart(“alternative”) object. To do this, create two separate message parts, with the plain text body as the first and the HTML body as the second part.

And that’s it, you’re ready to send your first email via Java, plain text or HTML.

How to send HTML emails with images?

Email keyboard key

In the previous section, we discussed how to turn your plain text email into an HTML one. But you may also want to enhance your email even further using images. Well, you can do that with Jakarta Mail too.

Jakarta Mail provides you with three ways to add images to your HTML email:

  • CID image embedding
  • inline embedding or Base64 encoding
  • llinked images
  1. To do CID image embedding, create a MIME multipart/related message using the code sample below:

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

  1. To use inline embedding (a.k.a. Base64 encoding), include the data of the encoded image in the HTML body:

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

Note: Keep in mind that inline image embedding can make your HTML message quite long, as each Base64 digit contains 6 bits of data. Naturally, this affects the size of your email, so Base64 encoding is not the best way to embed images.

  1. Linked images are simply images hosted on an external server, which you can link to in your email using the img tag in the HTML body, like in the following example:

<img src=”/wp-content/uploads/2018/11/blog/-illustration-email-embedding-images.png” alt=”img” />

Here is a full example of the code for an HTML email with a linked image:

package com.example.smtp;

import java.util.Properties;

import jakarta.mail.Message;

import jakarta.mail.MessagingException;

import jakarta.mail.PasswordAuthentication;

import jakarta.mail.Session;

import jakarta.mail.Transport;

import jakarta.mail.internet.InternetAddress;

import jakarta.mail.internet.MimeMessage;

 

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 jakarta.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(

“<p> The text and the <strong>image</strong>

<img src=”/wp-content/uploads/2018/11/blog/-illustration-email-embedding-images.png” alt=”img” /> ”

,

“text/html”);

// Send message

Transport.send(message);

System.out.println(“Sent message successfully….”);

} catch (MessagingException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

}

How to send emails with attachments?

In Jakarta Mail, attaching files to your emails is easy, and you can do that using the already familiar MimeMultipart object. The main part of the object is the text, while the second part is the attachment, which can be a file of any type, like .txt, .png, or any other.

To add an attachment to your email, use the following code:

package jakartaemail;

import java.util.Properties;

import jakarta.mail.Message;

import jakarta.mail.MessagingException;

import jakarta.mail.PasswordAuthentication;

import jakarta.mail.Session;

import jakarta.mail.Transport;

import jakarta.mail.internet.InternetAddress;

import jakarta.mail.internet.MimeMessage;

import jakarta.mail.BodyPart;

import jakarta.mail.Multipart;

import jakarta.mail.internet.MimeBodyPart;

import jakarta.mail.internet.MimeMultipart;

import jakarta.activation.DataSource;

import jakarta.activation.DataHandler;

import jakarta.activation.FileDataSource;

 

public class JakartaEmail {

public static void main(String[] args) {

//provide recipient’s email ID

String to = “jakartato@example.com”;

//provide sender’s email ID

String from = “jakartafrom@example.com”;

//provide Mailtrap’s username

final String username = “a094ccae2cfdb3”;

//provide Mailtrap’s password

final String password = “82a851fcf4aa33”;

//provide Mailtrap’s host address

String host = “smtp.mailtrap.io”;

//configure Mailtrap’s SMTP server details

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”, “587”);

//create the Session object

Session session = Session.getInstance(props,

new jakarta.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);

}

});

try {

//create a MimeMessage object

Message message = new MimeMessage(session);

//set From email field

message.setFrom(new InternetAddress(from));

//set To email field

message.setRecipients(Message.RecipientType.TO,

InternetAddress.parse(to));

//set email subject field

message.setSubject(“Here comes an attachment!”);

//create the message body part

BodyPart messageBodyPart = new MimeBodyPart();

//set the actual message

messageBodyPart.setText(“Please find the attachment sent using Jakarta Mail”);

//create an instance of multipart object

Multipart multipart = new MimeMultipart();

//set the first text message part

multipart.addBodyPart(messageBodyPart);

//set the second part, which is the attachment

messageBodyPart = new MimeBodyPart();

String filename = “C:\\Users\\OPIDI\\Desktop\\File 1\\gantt2.png”;

DataSource source = new FileDataSource(filename);

messageBodyPart.setDataHandler(new DataHandler(source));

messageBodyPart.setFileName(filename);

multipart.addBodyPart(messageBodyPart);

//send the entire message parts

message.setContent(multipart);

//send the email message

Transport.send(message);

System.out.println(“Email Message Sent Successfully”);

} catch (MessagingException e) {

throw new RuntimeException(e);

}

}

}

Those of you using a newer version of Jakarta Mail can replace the following piece of code with methods:

messageBodyPart = new MimeBodyPart();

String filename = “C:\\Users\\OPIDI\\Desktop\\File 1\\gantt2.png”;

DataSource source = new FileDataSource(filename);

messageBodyPart.setDataHandler(new DataHandler(source));

messageBodyPart.setFileName(filename);

multipart.addBodyPart(messageBodyPart);

Note: These methods are available in Jakarta Mail 1.4 and above and are intended to make attaching files much easier:

void attachFile(File file)

void attachFile(String filePath)

This is how our code will look like after we shorten it using the above methods:

messageBodyPart = new MimeBodyPart();

String filename = “C:\\Users\\OPIDI\\Desktop\\File 1\\gantt2.png”;

messageBodyPart.attachFile(filename);

multipart.addBodyPart(messageBodyPart);

Both ways of adding an attachment to your email work, so you have the freedom to choose the one that is a better fit for you, if you’re using Jakarta Mail 1.4 or later versions.

How to send emails to multiple recipients?

When it comes to including multiple recipients in your email using Jakarta Mail, the process is really simple.

The process entails using the setRecipients method, which we’ve already used in our previous code examples, only this time, you need to include an array of receiving email addresses instead of just one.

Here is an example of how the code should look like:

Address[] toAddresses = new InternetAddress[] {

new InternetAddress(“abc@abc.example”),

new InternetAddress(“abc@def.example”),

new InternetAddress(“ghi@abc.example”)};

message.setRecipients(Message.RecipientType.TO, toAddresses);

An alternative to setRecipients is the addRecipients method, which works in a similar way. But for the sake of consistency, we’re sticking to setRecipients throughout this article’s code examples.

More options for sending emails in Java

While it’s not difficult to set up email sending via Jakarta Mail API manually, this can take some time. Therefore, we’re introducing you to tools that will help you send emails via Java simpler and faster.

Spring Framework

Spring is a powerful library designed to simplify emailing in Java by encapsulating the complexities of the JavaMail API.

The main email package in Spring is org.springframework.mail, and for handling MIME features, you can use org.springframework.mail.javamail.MimeMessagePreparator.

To get started with Spring, the first step is to add the dependency to your project. You can do this through either Maven or Gradle.

You can find the required code on the Maven Repository page or add the one below code to your pom.xml file:

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

<version>5.3.23</version>

</dependency>

Once you’ve added the dependency, simply copy and paste the following code into your project to add server properties:

@Bean

public JavaMailSender getJavaMailSender() {

JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

mailSender.setHost(“smtp.mailtrap.io”);

mailSender.setPort(2525);

mailSender.setUsername(“1a2b3v4d5e6f7g”);

mailSender.setPassword(“1a2b3v4d5e6f7g”);

Properties props = mailSender.getJavaMailProperties();

props.put(“mail.transport.protocol”, “smtp”);

props.put(“mail.smtp.auth”, “true”);

props.put(“mail.smtp.starttls.enable”, “true”);

props.put(“mail.debug”, “true”);

return mailSender;

}

Simple email

@Component

public class EmailServiceImpl implements EmailService {

@Autowired

public JavaMailSender emailSender;

public void sendSimpleMessage(

String to, String subject, String text) {

SimpleMailMessage message = new SimpleMailMessage();

message.setTo(to);

message.setSubject(subject);

message.setText(text);

emailSender.send(message);

}

}:

Apache Commons Email

Apache Commons Email is a simplified version of the Jakarta Mail API designed for easier use. But despite its simplicity, it still supports classes that enable sending simple HTML emails, emails with attachments, or even emails that contain embedded images.

Not only can Apache Commons Email be used on its own, but it can also serve as a foundation for other email-based applications, such as the Play Framework and mailR for sending emails using R.

The first step to sending an email using Apache Commons Email is, as usual, to add the required dependency:

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-email</artifactId>

<version>1.5</version>

</dependency>

Then, you need to run the code below:

App.java

package app;

import org.apache.commons.mail.DefaultAuthenticator;

import org.apache.commons.mail.EmailException;

import org.apache.commons.mail.HtmlEmail;

 

public class App {

public static void main(String[] args) throws EmailException {

HtmlEmail mail = new HtmlEmail();

mail.setHostName(“smtp.mailtrap.io”);

mail.setSmtpPort(2525);

mail.setAuthenticator(new DefaultAuthenticator(“1a2b3c4d5e6f7g”, “1a2b3c4d5e6f7g”));

mail.setFrom(“from@example.com”, “From”);

mail.addTo(“to@example.com”, “To”);

mail.setSubject(“Apache Commons email test”);

mail.setHtmlMsg(“<p style=’font-size:16px;color:green’>Here is your example</p>”);

mail.send();

}

}

And that’s it — you’ve successfully sent your email using Java and Apache Commons Email.

Simple Java Mail

Lastly, we have Simple Java Mail, which, as its name suggests, is a very simple mailing library.

The library simplifies the Jakarta Mail API, eliminating the need for you to use various classes and properties. Simple Java Mail also offers support for HTML, images, attachments, and even templates.

Additionally, Simple Java Mail is secure and dependable, provides email signing capabilities with DKIM, utilizes S/MIME encryption, undergoes regular updates, and provides an extensive collection of code samples.

To try out the power of Simple Java Mail for sending emails in Java, simply add the dependency to your project:

<dependency>

<groupId>org.simplejavamail</groupId>

<artifactId>simple-java-mail</artifactId>

<version>7.8.2</version>

</dependency>

Then, use the short code excerpt below to create and send your email:

Email email = EmailBuilder.startingBlank()

.from(“From”, “from@example.com”)

.to(“To”, “to@example.com”)

.to(“You too”, “you@example.com”)

.withSubject(“Simple Java Mail testing!”)

.withPlainText(“Looks like it’s really simple!”)

.buildEmail();

MailerBuilder

.withSMTPServer(“smtp.mailtrap.io”, 2525, “1a2b3c4d5e6f7g”, “1a2b3c4d5e6f7g”)

.withTransportStrategy(TransportStrategy.SMTPS);

.buildMailer()

.sendMail(email);

Final words

Now you have a basic understanding of how to send emails with Java – manually and using tools. Along with that, you also know how to send emails containing images and attachments as well as emails intended for multiple recipients. Talk about a useful tutorial!

BIO:

Denys Kontorskyy: I am an experienced Technical Content Writer specializing in email infrastructure, offering insights on sending, testing, and optimizing emails. I also have a strong interest in product marketing, creating engaging content that drives audience engagement and supports business growth. With a focus on delivering effective campaigns and staying updated with industry trends, I bring a strategic approach to my writing that aims to achieve measurable results.

Have a Look at These Articles Too

Published on April 25, 2023 by Lucija; modified on July 13, 2023. Filed under: , , , , .

I used to write about games but now work on web development topics at WebFactory Ltd. I've studied e-commerce and internet advertising, and I'm skilled in WordPress and social media. I like design, marketing, and economics. Even though I've changed my job focus, I still play games for fun.

Leave a Reply