Send Email Using Spring

As part of the Spring Boot tutorial, in this article, we will see how to send email using Spring.

 

Introduction

Sending out email is a typical need for any application. In this article will learn the steps to send email using Spring. To work on this tutorial, you need SMTP details to send out the email. For the sample application, you can use Gmail smtp (keep in mind Gmail have a certain limitation on the email quota). The Spring Framework provides an easy abstraction for sending email by using the JavaMailSender interface, and Spring Boot provides auto-configuration for it and a starter module.

 

1. Maven Dependencies

We need to add the spring-boot-starter-mail in our pom.xml to enable Spring Boot auto-configuration for our application. This is the snapshot of our pom.xml:

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

 

2. Mail Configurations

Once we have the dependencies defined, the next step is to add the mail configurations  to be available to Spring Boot auto configuration:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username= gmail user name
spring.mail.password= your password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Above configurations values are for Gmail SMTP, replace these with your SMTP configurations:

 

3. Email Service

Let’s create a simple email service class to send out emails for our application. Our sample email service will contain 2 method:

  1. Send out simple emails
  2. Emails with attachment

This is how our code look like:

@Service
public class DefaultEmailService implements EmailService {

 @Autowired
 public JavaMailSender emailSender;

 @Override
 public void sendSimpleEmail(String toAddress, String subject, String message) {

  SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
  simpleMailMessage.setTo(toAddress);
  simpleMailMessage.setSubject(subject);
  simpleMailMessage.setText(message);
  emailSender.send(simpleMailMessage);
 }

 @Override
 public void sendEmailWithAttachment(String toAddress, String subject, String message, String attachment) throws MessagingException, FileNotFoundException {

  MimeMessage mimeMessage = emailSender.createMimeMessage();
  MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
  messageHelper.setTo(toAddress);
  messageHelper.setSubject(subject);
  messageHelper.setText(message);
  FileSystemResource file = new FileSystemResource(ResourceUtils.getFile(attachment));
  messageHelper.addAttachment("Purchase Order", file);
  emailSender.send(mimeMessage);
 }
}

 

4. Test Controller

Let’s create a simple REST controller to check our work. Our REST controller will have 2 methods. This is how our controller look like:

package com.javadevjournal.controller;

import com.javadevjournal.email.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.MailException;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.io.FileNotFoundException;

@RestController
@RequestMapping("/email")
public class EmailController {

    private static final Logger LOG = LoggerFactory.getLogger(EmailController.class);

    @Autowired
    EmailService emailService;

    @GetMapping(value = "/simple-email/{user-email}")
    public @ResponseBody ResponseEntity sendSimpleEmail(@PathVariable("user-email") String email) {

        try {
            emailService.sendSimpleEmail(email, "Welcome", "This is a welcome email for your!!");
        } catch (MailException mailException) {
            LOG.error("Error while sending out email..{}", mailException.getStackTrace());
            return new ResponseEntity<>("Unable to send email", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new ResponseEntity<>("Please check your inbox", HttpStatus.OK);
    }

    @GetMapping(value = "/simple-order-email/{user-email}")
    public @ResponseBody ResponseEntity sendEmailAttachment(@PathVariable("user-email") String email) {

        try {
            emailService.sendEmailWithAttachment(email, "Order Confirmation", "Thanks for your recent order",
                    "classpath:purchase_order.pdf");
        } catch (MessagingException | FileNotFoundException mailException) {
            LOG.error("Error while sending out email..{}", mailException.getStackTrace());
            return new ResponseEntity<>("Unable to send email", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new ResponseEntity<>("Please check your inbox for order confirmation", HttpStatus.OK);
    }

}

 

5. Spring Boot Main Class

@SpringBootApplication
public class SendEmailUsingSpringApplication {

   public static void main(String[] args) {
      SpringApplication.run(SendEmailUsingSpringApplication.class, args);
   }

}

Run our application and hit the following URL‘s :

http://localhost:8080/email/order-email/[email protected]
http://localhost:8080/email/simple-email/[email protected]

 

6. Gmail SMTP

If you are using Gmail SMTP, please refer to the following URL for detail. Your normal email password will not work because of added security in Gmail.

 

Summary

In this article, we learned how to send email using Spring. We saw how to use Spring Boot auto-configuration to make it more easy and flexible for the email functionality. The source code for this post is available on GitHub.

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of