Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - Sending Email via SMTP

Sending emails from a Spring Boot application is a common requirement, and Spring provides easy-to-use support for sending emails via SMTP using the JavaMailSender interface. Here's a guide to help you send emails from a Spring Boot application:

1. Add Dependencies

Add the required dependencies to your pom.xml:

<!-- Spring Boot Starter for Mail -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!-- (Optional) Apache Commons Email for easier email composition -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-email</artifactId>
    <version>1.5</version>
</dependency>

2. Configure Mail Properties

Configure your SMTP server details in application.properties or application.yml.

# SMTP server details
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=myemail@example.com
spring.mail.password=mypassword

# Additional properties
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Replace with your SMTP server details and credentials.

3. Create Email Service

Create a service to send emails:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    public void sendSimpleEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        
        mailSender.send(message);
    }
}

If you want to send emails with attachments or HTML content, you'd use MimeMessage instead of SimpleMailMessage.

4. Send an Email

Now you can use the EmailService to send an email:

@Autowired
private EmailService emailService;

public void someMethod() {
    emailService.sendSimpleEmail("recipient@example.com", "Test Subject", "This is a test email.");
}

5. Handling Attachments and HTML Content

If you wish to send emails with attachments or HTML content, you would need to construct a MimeMessage:

import org.springframework.mail.javamail.MimeMessageHelper;

public void sendEmailWithAttachment(String to, String subject, String text, String pathToAttachment) {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text);

    FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
    helper.addAttachment("filename.txt", file);

    mailSender.send(message);
}

Conclusion

Using Spring Boot to send emails is quite straightforward. The provided abstraction simplifies many complexities of sending emails, allowing developers to focus on the core functionality of their applications.

  1. Configuring SMTP properties in Spring Boot:

    • Description: Configure SMTP properties in the application.properties or application.yml file to enable Spring Boot to send emails through an SMTP server.
    • Code:
      # SMTP configuration in application.properties
      spring.mail.host=smtp.example.com
      spring.mail.port=587
      spring.mail.username=user@example.com
      spring.mail.password=secretpassword
      spring.mail.properties.mail.smtp.auth=true
      
  2. Using JavaMailSender for email sending in Spring Boot:

    • Description: Spring Boot simplifies email sending with the JavaMailSender interface. Autowire it in your service and use it to send emails.
    • Code:
      // Example using JavaMailSender in Spring Boot
      @Service
      public class EmailService {
          @Autowired
          private JavaMailSender javaMailSender;
      
          public void sendEmail(String to, String subject, String body) {
              SimpleMailMessage message = new SimpleMailMessage();
              message.setTo(to);
              message.setSubject(subject);
              message.setText(body);
              javaMailSender.send(message);
          }
      }
      
  3. Sending HTML emails with Thymeleaf in Spring Boot:

    • Description: Use Thymeleaf templating engine to send HTML emails in Spring Boot. Create HTML templates and merge them with dynamic data.
    • Code:
      // Example sending HTML email with Thymeleaf in Spring Boot
      @Service
      public class EmailService {
          @Autowired
          private JavaMailSender javaMailSender;
          @Autowired
          private TemplateEngine templateEngine;
      
          public void sendHtmlEmail(String to, String subject, Map<String, Object> model) {
              MimeMessage message = javaMailSender.createMimeMessage();
              MimeMessageHelper helper = new MimeMessageHelper(message, true);
              helper.setTo(to);
              helper.setSubject(subject);
      
              String htmlContent = templateEngine.process("email-template.html", new Context(Locale.getDefault(), model));
              helper.setText(htmlContent, true);
      
              javaMailSender.send(message);
          }
      }
      
  4. Attaching files to emails in Spring Boot with SMTP:

    • Description: Attach files to emails using MimeMessageHelper in Spring Boot. This is useful for sending documents or images as email attachments.
    • Code:
      // Example attaching files to email in Spring Boot
      @Service
      public class EmailService {
          @Autowired
          private JavaMailSender javaMailSender;
      
          public void sendEmailWithAttachment(String to, String subject, String body, String attachmentPath) {
              MimeMessage message = javaMailSender.createMimeMessage();
              MimeMessageHelper helper = new MimeMessageHelper(message, true);
              helper.setTo(to);
              helper.setSubject(subject);
              helper.setText(body);
      
              FileSystemResource file = new FileSystemResource(new File(attachmentPath));
              helper.addAttachment("AttachmentName", file);
      
              javaMailSender.send(message);
          }
      }
      
  5. Handling email templates and placeholders in Spring Boot:

    • Description: Use placeholders in email templates to dynamically fill in data. Spring Boot and Thymeleaf make it easy to replace placeholders with actual values.
    • Code:
      <!-- Example Thymeleaf email template -->
      <p>Hello, [[${name}]]!</p>
      
  6. Secure email communication with TLS and SSL in Spring Boot:

    • Description: Enable secure communication with SMTP servers by configuring TLS or SSL properties in Spring Boot.
    • Code:
      # TLS configuration in application.properties
      spring.mail.properties.mail.smtp.starttls.enable=true
      
  7. Scheduling email tasks with Spring Boot:

    • Description: Schedule email tasks using Spring's scheduling features. For example, use @Scheduled to send daily reports or reminders.
    • Code:
      // Example scheduling email task in Spring Boot
      @Service
      public class EmailService {
          @Autowired
          private JavaMailSender javaMailSender;
      
          @Scheduled(cron = "0 0 8 * * ?") // Run every day at 8 AM
          public void sendDailyReport() {
              // Task logic to send daily report email
          }
      }
      
  8. Error handling and logging for email sending in Spring Boot:

    • Description: Implement error handling and logging to track email sending failures or issues. This helps in diagnosing and resolving problems.
    • Code:
      // Example error handling and logging in Spring Boot email service
      @Service
      public class EmailService {
          private static final Logger logger = LoggerFactory.getLogger(EmailService.class);
      
          @Autowired
          private JavaMailSender javaMailSender;
      
          public void sendEmail(String to, String subject, String body) {
              try {
                  SimpleMailMessage message = new SimpleMailMessage();
                  message.setTo(to);
                  message.setSubject(subject);
                  message.setText(body);
                  javaMailSender.send(message);
              } catch (Exception e) {
                  logger.error("Error sending email: {}", e.getMessage());
                  // Handle the error, e.g., send a notification or log it
              }
          }
      }