eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this quick tutorial, we’re going to look at sending an email with and without attachments using the core Java mail library.

2. Project Setup and Dependency

For this article, we’ll be using a simple Maven-based project with Angus Mail as its dependency. In detail, this library is the Eclipse implementation of the Jakarta Mail API specification:

<dependency>
    <groupId>org.eclipse.angus</groupId>
    <artifactId>angus-mail</artifactId>
    <version>2.0.1</version>
</dependency>

The latest version can be found here.

3. Sending a Plain Text and an HTML Email

First, we need to configure the library with our email service provider’s credentials. Then, we’ll create a Session that’ll be used to construct our message for sending.

The configuration is via a Java Properties object:

Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "sandbox.smtp.mailtrap.io");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "sandbox.smtp.mailtrap.io");

In the properties configuration above, we configured the email host as Mailtrap and used the port provided by the service as well.

Note: To set up the configurations above correctly, we must check the official documentation from Mailtrap, as the host may vary depending on the type of SMTP integration we want to achieve.

Now, let’s create a session with our username and password:

Session session = Session.getInstance(prop, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
});

The username and password are given by the mail service provider alongside the host and port parameters.

Now that we have a mail Session object let’s create a MimeMessage for sending:

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(
  Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Mail Subject");

String msg = "This is my first email using JavaMailer";

MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);

message.setContent(multipart);

Transport.send(message);

In the snippet above, we first created a message instance with the necessary properties to, from, and subject. This is followed by a mimeBodyPart that has an encoding of text/html since our message is styled in HTML.

Next, we created an instance of the MimeMultipart object that we can use to wrap the mimeBodyPart we created.

Finally, we set the multipart object as the content of our message and used the send() of the Transport object to send mail.

So, we can say that the mimeBodyPart is contained in the message‘s multipart. A multipart can contain more than one mimeBodyPart.

This is going to be the focus of the next section.

4. Sending Email With an Attachment

Next, to send an attachment, we only need to create another MimeBodyPart and attach the file(s) to it:

MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(new File("path/to/file"));

We can then add the new body part to the MimeMultipart object we created earlier:

multipart.addBodyPart(attachmentBodyPart);

That’s all we need to do.

Once again, we set the multipart instance as the content of the message object, and finally, we’ll use the send() to send the mail.

5. Formatting Email Text

To format and style our email text, we can use HTML and CSS tags.

For example, if we want our text to be bold, we will implement the <b> tag. We can use the style tag to color the text. We can also combine HTML tags with CSS tags if we want to have additional properties, such as bold.

Let’s create a String containing bold-red text:

String msgStyled = "This is my <b style='color:red;'>bold-red email</b> using JavaMailer";

This String will hold our styled text to be sent in the email body.

6. Sending Email to Multiple Recipients

To send emails to multiple recipients, we can use the setRecipients() and addRecipients() methods which take an array of recipient addresses and recipient types such as TO, CC, and BCC  :

6.1. Using setRecipients() 

We can set multiple recipients using the setRecipients() method. For the recipient list, we can pass the recipient type and the array of recipient addresses as arguments:

Address[] recipients = new InternetAddress[2];
recipients[0] = new InternetAddress("[email protected]");
recipients[1] = new InternetAddress("[email protected]");

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

Additionally, we can also use InternetAddress.parse() method to pass the CSV of the email address as strings:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected], [email protected]"));

The parse() method converts the CSV of email addresses to an InternetAddress instance.

6.2. Using addRecipients()

addRecipients() is another method that allows us to add multiple recipients to the email Message instance. The main difference between the setRecipients() and addRecipients() methods is that the setRecipients() method overrides any existing set recipient and starts a fresh recipient list, while the addRecipient() method adds the recipient to the existing recipients if there is any already set.

Let’s add more recipients on top of what we set in the earlier section:

Address[] recipients1 = new InternetAddress[2]; 
recipients1[0] = new InternetAddress("[email protected]"); 
recipients1[1] = new InternetAddress("[email protected]");

message.addRecipients(Message.RecipientType.TO, recipients1);

Additionally, similar to the earlier section, we can also use the InternetAddress.parse() method to pass the CSV of the email address as strings:

message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected], [email protected]"));

The parse() method converts the CSV of email addresses to an InternetAddress instance.

7. Setting Connection Timeout

When working with email services, it’s crucial to handle network issues gracefully, especially when the mail server is slow to respond or unreachable. JavaMail allows us to configure connection timeouts using additional properties.

To set timeouts, we can add the following entries to the Properties object:

prop.put("mail.smtp.connectiontimeout", "10000");
prop.put("mail.smtp.timeout", "10000");
prop.put("mail.smtp.writetimeout", "10000");

In the example above, we used three specific timeout properties:

  • mail.smtp.connectiontimeout: The time to wait when establishing a connection to the SMTP server.
  • mail.smtp.timeout: The time to wait when reading from the server.
  • mail.smtp.writetimeout: The time to wait when writing data to the server.

By setting these properties, we prevent the application from hanging indefinitely if the SMTP server becomes unresponsive or slow. Once set, these timeout configurations apply automatically during the email sending process.

8. Ignoring Server Certificate Errors

When working in development environments with untrusted or self-signed certificates or testing setups, we might encounter SSL/TLS certificate validation errors.

To bypass this in JavaMail, we can disable strict certificate checks by setting two properties:

prop.put("mail.smtp.ssl.trust", "*");
prop.put("mail.smtp.ssl.checkserveridentity", false);

These configurations disable Java’s default certificate validation process, allowing connections to servers with invalid or self-signed certificates.

Alternately, for cases where using the SMTPS protocol, set the mail.smtp.ssl.trust=”*” isn’t enough. We can configure JavaMail to use a custom SSLSocketFactory that accepts all certificates:

TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
        public X509Certificate[] getAcceptedIssuers() { 
            return new X509Certificate[0];
        }
    }
};

Next, we need to initialize a custom SSLSocketFactory:

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

Then we set the socket factory in the properties:

props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
props.put("mail.smtp.ssl.trust", "*");

This approach completely disables SSL certificate validation.

However, this should only be used in testing environments. For production, always use a valid SSL certificate from a trusted Certificate Authority (CA) to ensure secure communication.

9. Conclusion

In this article, we’ve seen how to use the Jakarta Mail API to send emails, even with attachments. Additionally, we also learned how to send emails to multiple recipients.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)