Send emails in Spring Boot

If you are looking for a fast tutorial on how to send emails in Spring Boot applications, then you landed in the right place 😀

1) Add the spring-boot-starter-mail dependency to the pom.xml file

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

2) Configure a mail server for testing purposes. I would recommend Mailtrap, a free online service for testing email features in your projects. I love using it and you can check out my review of Mailtrap in this article. You will need the following properties:

  • hostname
  • port
  • username
  • password

In Mailtrap, you can grab them in your Test Inbox.

Mailtrap Configuration

springbootemail-mailtrap

3) Add the email server configuration in the application.properties file. Here, we will use the Mailtrap config, but the actual values will be different in your application, depending on your email server.

spring.mail.host=smtp.mailtrap.io
spring.mail.port=2525
spring.mail.username=87ad5806d46a7e
spring.mail.password=564ee41ac808c0

4) Bind the application properties to a configuration class for better reuse in code. This step is optional, but it can simplify the reuse of mail settings across your project.

package rc.mail.feedback;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class EmailCfg {
    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.port}")
    private int port;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

5) Create a REST controller method that will send emails. You can use any method, but because we are using Spring Boot, the actual code that will send emails is located inside a REST controller.

package rc.mail.feedback;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ValidationException;

@RestController
@RequestMapping("/feedback")
public class FeedbackController {

    private EmailCfg emailCfg;

    public FeedbackController(EmailCfg emailCfg) {
        this.emailCfg = emailCfg;
    }

    @PostMapping
    public void sendFeedback(@RequestBody Feedback feedback,
                             BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new ValidationException("Feedback is not valid");
        }

        // Create a mail sender
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(this.emailCfg.getHost());
        mailSender.setPort(this.emailCfg.getPort());
        mailSender.setUsername(this.emailCfg.getUsername());
        mailSender.setPassword(this.emailCfg.getPassword());

        // Create an email instance
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(feedback.getEmail());
        mailMessage.setTo("rc@feedback.com");
        mailMessage.setSubject("New feedback from " + feedback.getName());
        mailMessage.setText(feedback.getFeedback());

        // Send mail
        mailSender.send(mailMessage);
    }
}
package rc.mail.feedback;

import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

public class Feedback {
    @NotNull
    private String name;

    @NotNull
    @Email
    private String email;

    @NotNull
    @Min(10)
    private String feedback;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFeedback() {
        return feedback;
    }

    public void setFeedback(String feedback) {
        this.feedback = feedback;
    }
}

That’s it:) You can now send emails by making a REST call to http://localhost:<port>/feedback with the appropriate data.

POST http://localhost:8082/feedback
Content-Type: application/json

{
  "name": "Dan",
  "email": "dan@gmail.com",
  "feedback": "You app is awesome :)"
}