Sending email from your Spring Boot app

1. Overview

In this article I’ll show you how you can send email from your spring boot app using JavaMailSender interface. It’s an abstraction for sending emails from spring boot that provides auto configuration and easy implementation. I’m using a gmail account here to demonstrate the process.

2. Depencency

Add spring-boot starter-mail dependency on your pom.xml file.


3. Mail Properties

Add your email credentials on your file.

#spring-boot-starter-mail properties
[email protected]

4. Configuration

Write a configuration class so that you can configure your JavaMailSender bean with your email credentials and properties.

public class MailConfig {
    private String host;

    private Integer port;
    private String username;
    private String password;

    public JavaMailSender javaMailService() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();



        return javaMailSender;

    private Properties getMailProperties() {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.debug", "false");
        return properties;


If you defined your email properties into another properties file like “” you need to add @PropertySource(“”) on your class.


5. Email Service –

Okay, now that we’ve configured our JavaMailSender bean with our credentials. We can use this bean to send email. Write a class that sends email to an address.

public class MailService {

    private JavaMailSender javaMailSender;

    public void sendEmail(String email,String message) throws Exception{
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setSubject("Response from Autism Barta");


6. Use MailService Bean to Send Email

Now everything is ready, you can now inject your MailService bean to your class and send email using it’s sendEmail() method.

public class EmailController {

    private MailService mailService;

    @RequestMapping(value = "/email/send", method = RequestMethod.POST)
    private String sendEmailToUser(@ModelAttribute User user,
                                   @RequestParam("message") String message) {
        try {
            this.mailService.sendEmail(user.getEmail(), message);
        } catch (Exception e) {
            // handle your exception when it fails to send email
        return "redirect:/";


7. Conclusion

That was easy, right? May be you may like some other articles like deploying Spring Boot app using Docker, or Authenticating users using Spring Security.

Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *