How to send email in Spring Boot Project via SMTP

To send an email using SMTP in Spring MVC or Spring Boot projects is pretty simple. In this post, I am going to share an easy method to send email in Spring projects.

Add Maven Dependency

black and gray digital device
Photo by Torsten Dettlaff on (How to Send An Email in Spring Boot Project)

Add spring-boot-starter-mail dependency on your project. It has all the packages that you require to send an email in Spring or Spring Boot project.

Here is a code snippet showing examples of how to add spring-boot-starter-mail to your project. Add the following code snippet to your pox.xml file.

</dependency>Code language: HTML, XML (xml)

Modify file

If you are done importing the maven package to your project, now you are ready to configure how to send an email from your Spring project.

To do this, first, modify your file as shown below:

# Other properties

# TLS , port 587

# SSL, post 465 = 465 = language: PHP (php)

Sending Email using JavaMailSender

Here is an example showing how to use JavaMailSender to send emails in Spring Boot.

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

private JavaMailSender javaMailSender;
	void sendEmail() {

        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setTo("", "", "");

        msg.setSubject("Testing from Spring Boot");
        msg.setText("Hello World \n Spring Boot Email");


}Code language: Java (java)

Sending Email With Attachments

To send an email with attachments in Spring project, we should use a MIME multipart message from the JavaMail library instead of SimpleMailMessage (shown in the code snippet above).

Spring supports JavaMail messaging with the org.springframework.mail.javamail.MimeMessageHelper class.

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

    helper.setSubject("Testing from Spring Boot");
    helper.setText("Hello World \n Spring Boot Email");
    FileSystemResource file 
      = new FileSystemResource(new File(pathToAttachment));
    helper.addAttachment("Invoice", file);

    // ...
}Code language: JavaScript (javascript)

Leave a Reply

Discover more from BHUTAN IO

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top