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

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll walk through the steps needed to send emails from both a plain vanilla Spring application as well as a Spring Boot application. For the former, we’ll use the JavaMail library, and the latter will use the spring-boot-starter-mail dependency.

Further reading:

Registration - Activate a New Account by Email

Verify newly registered users by sending them a verification token via email before allowing them to log in - using Spring Security.

Spring Boot Actuator

A quick intro to Spring Boot Actuators - using and extending the existing ones, configuration and rolling your own.

2. Maven Dependencies

First, we need to add the dependencies to our pom.xml.

2.1. Spring

Here is what we’ll add for use in the plain vanilla Spring framework:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>6.2.12</version>
</dependency>

The latest version can be found here.

2.2. Spring Boot

And for Spring Boot:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>3.5.7</version>
</dependency>

The latest version is available in the Maven Central repository.

3. Mail Server Properties

The interfaces and classes for Java mail support in the Spring framework are organized as follows:

  1. MailSender interface: the top-level interface that provides basic functionality for sending simple emails
  2. JavaMailSender interface: the subinterface of the above MailSender. It supports MIME messages and is mostly used in conjunction with the MimeMessageHelper class for the creation of a MimeMessage. It’s recommended to use the MimeMessagePreparator mechanism with this interface.
  3. JavaMailSenderImpl class provides an implementation of the JavaMailSender interface. It supports the MimeMessage and SimpleMailMessage.
  4. SimpleMailMessage class: used to create a simple mail message including the from, to, cc, subject and text fields
  5. MimeMessagePreparator interface provides a callback interface for the preparation of MIME messages.
  6. MimeMessageHelper class: helper class for the creation of MIME messages. It offers support for images, typical mail attachments and text content in an HTML layout.

In the following sections, we show how to use these interfaces and classes.

3.1. Spring Mail Server Properties

Mail properties that are needed to specify, for example, the SMTP server may be defined using the JavaMailSenderImpl.

For Gmail, this can be configured as shown below:

@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(587);
    
    mailSender.setUsername("[email protected]");
    mailSender.setPassword("password");
    
    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;
}

3.2. Spring Boot Mail Server Properties

Once the dependency is in place, the next step is to specify the mail server properties in the application.properties file using the spring.mail.* namespace.

We can specify the properties for the Gmail SMTP server this way:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<login user to smtp server>
spring.mail.password=<login password to smtp server>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Some SMTP servers require a TLS connection, so we use the property spring.mail.properties.mail.smtp.starttls.enable to enable a TLS-protected connection.

3.2.1. Gmail SMTP Properties

We can send an email via Gmail SMTP server. Have a look at the documentation to see the Gmail outgoing mail SMTP server properties.

Our application.properties file is already configured to use Gmail SMTP (see the previous section).

Note that the password for our account should not be an ordinary password but an application password generated for our Google account. Follow this link to see the details and to generate your Google App Password.

3.2.2. SES SMTP Properties

To send emails using Amazon SES, we set our application.properties:

spring.mail.host=email-smtp.us-west-2.amazonaws.com
spring.mail.username=username
spring.mail.password=password
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=25
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

Please be aware that Amazon requires us to verify our credentials before using them. Follow the link to verify your username and password.

4. Sending Email

Once dependency management and configuration are in place, we can use the aforementioned JavaMailSender to send an email.

Since both the plain vanilla Spring framework as well as the Boot version of it handle the composing and sending of emails in a similar way, we won’t have to distinguish between the two in the subsections below.

4.1. Sending Simple Emails

Let’s first compose and send a simple email message without any attachments:

@Component
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender emailSender;

    public void sendSimpleMessage(
      String to, String subject, String text) {
        ...
        SimpleMailMessage message = new SimpleMailMessage(); 
        message.setFrom("[email protected]");
        message.setTo(to); 
        message.setSubject(subject); 
        message.setText(text);
        emailSender.send(message);
        ...
    }
}

Note that even though it’s not mandatory to provide the from address, many SMTP servers would reject such messages. That’s why we use the [email protected] email address in our EmailService implementation.

4.2. Sending Emails With Attachments

Sometimes Spring’s simple messaging is not enough for our use cases.

For example, we want to send an order confirmation email with an invoice attached. In this case, we should use a MIME multipart message from JavaMail library instead of SimpleMailMessage. Spring supports JavaMail messaging with the org.springframework.mail.javamail.MimeMessageHelper class.

First of all, we’ll add a method to the EmailServiceImpl to send emails with attachments:

@Override
public void sendMessageWithAttachment(
  String to, String subject, String text, String pathToAttachment) {
    // ...
    
    MimeMessage message = emailSender.createMimeMessage();
     
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    
    helper.setFrom("[email protected]");
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text);
        
    FileSystemResource file 
      = new FileSystemResource(new File(pathToAttachment));
    helper.addAttachment("Invoice", file);

    emailSender.send(message);
    // ...
}

4.3. Simple Email Template

SimpleMailMessage class works well with String formatting.

We can create a template for emails by defining a template bean in our configuration:

@Bean
public SimpleMailMessage templateSimpleMessage() {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setText(
      "This is the test email template for your email:\n%s\n");
    return message;
}

Now we can use this bean as a template for email and only need to provide the necessary parameters to the template:

@Autowired
public SimpleMailMessage template;
...
String text = String.format(template.getText(), templateArgs);  
sendSimpleMessage(to, subject, text);

4.4. Send Email Attachment Using InputStream

In scenarios where we need to send an attachment that we generate dynamically or is available as an InputStream, we can leverage the MimeMessageHelper class from the Spring framework.

To implement sending an email with an attachment sourced from an InputStream, we can add the following method to the EmailServiceImpl class:

public void sendMessageWithInputStreamAttachment(
  String to, String subject, String text, String attachmentName, InputStream attachmentStream) {
    try {
        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom("[email protected]");
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);

        // Add the attachment from InputStream
        helper.addAttachment(attachmentName, new InputStreamResource(attachmentStream));

        emailSender.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

The method starts by creating a MimeMessage instance using JavaMailSender. MimeMessageHelper is initialized with MimeMessage, allowing for multipart messages which are necessary for attachments.

The attachment is added using addAttachment(), where InputStreamResource is used to wrap the provided InputStream. This enables attaching data that may not be stored as a file.

Now we can call this method:

InputStream attachmentStream = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8));
emailService.sendMessageWithInputStreamAttachment(
  "[email protected]", 
  "Subject Here", 
  "Body of the email", 
  "attachment.txt", 
  attachmentStream);

In this example, a simple string is converted into an InputStream, which is then sent as an attachment named “attachment.txt“. This method provides flexibility for sending various types of content as attachments without needing to save them as files on disk first.

5. Handling Send Errors

JavaMail provides SendFailedException to handle situations when a message cannot be sent. But it is possible that we won’t get this exception while sending an email to the incorrect address. The reason is the following:

The protocol specs for SMTP in RFC 821 specifies the 550 return code that the SMTP server should return when attempting to send an email to the incorrect address. But most of the public SMTP servers don’t do this. Instead, they send a “delivery failed” email or give no feedback at all.

For example, Gmail SMTP server sends a “delivery failed” message. And we get no exceptions in our program.

So, we have a few options to handle this case:

  1. Catch the SendFailedException, which can never be thrown.
  2. Check our sender mailbox for the “delivery failed” message for some period of time. This is not straightforward, and the time period is not determined.
  3. If our mail server gives no feedback at all, we can do nothing.

6. Conclusion

In this quick article, we showed how to set up and send emails from a Spring Boot application.

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=Spring)
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)