Spring Boot: Sending Emails

The ability to send emails is an integral part of any web application. Sometimes emails need to be sent for order confirmation. Another use case is to notify a development team when certain error conditions are met. Either way, sending emails are important.

To do this with Spring Boot, we must first have the correct dependencies. We will use Maven for this tutorial. Navigate to your pom.xml and add these dependencies:

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

With Linux, we could install sendmail but we will use gmail’s SMTP server for simplicity. We must first append the following info to our application.properties file:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username={gmail_user_name}
spring.mail.password={gmail_password}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

Now we must create our interface for dependency injection:

public interface EmailService {
    void send(String from, String to, String title, String body);
}

The next step is to create the implementation:

@Service
public class EmailServiceImpl implements EmailService {
    private JavaMailSender javaMailSender;

    @Autowired
    public EmailServiceImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public void send(String from, String to, String title, String body) {
        MimeMessage message = this.javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message);
        try {
            if (from != null) {
                mimeMessageHelper.setFrom(from);
            }
            mimeMessageHelper.setSubject(title);
            mimeMessageHelper.setText(body);
            mimeMessageHelper.setTo(to);
            this.javaMailSender.send(message);
        } catch (MessagingException messageException) {
            // You could also 'throw' this exception. I am not a fan of checked exceptions. 
            // If you want to go that route, then just update this method and the interface. 
            throw new RuntimeException(messageException);
        }
    }
}

Finally, we are setup for emailing. Now you can use this service to send emails!

Leave a Reply

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