Introduction
During this exercise we will use the Spring Boot Starter for sending mail
Background info
Spring Boot Starters are all those dependencies which are started with spring-boot-starter and are used in Spring Boot to get you started with some part of the Spring framework e.g. Data, JDBC, Test and Web
Overview for sending email using Spring Boot Starter Mail
In this article, we’ll walk through the steps needed to send emails from both a plain vanilla Spring application as well as from a Spring Boot application, the former using the JavaMail library and the latter using the spring-boot-starter-mail dependency.
Maven dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Mail Server Properties
-
MailSender interface
-
The top-level interface that provides basic functionality for sending simple emails
-
-
JavaMailSender interface
-
the subinterface of the above MailSender. It supports MIME messages and is mostly used in conjunction with the MimeMessageHelper class for the creation of a MimeMessage. It’s recommended to use the MimeMessagePreparator mechanism with this interface
-
-
JavaMailSenderImpl class
-
provides an implementation of the JavaMailSender interface. It supports the MimeMessage and SimpleMailMessage
-
-
SimpleMailMessage class
-
used to create a simple mail message including the from, to, cc, subject and text fields
-
-
MimeMessagePreparator interface
-
provides a callback interface for the preparation of MIME messages
-
-
MimeMessageHelper class
-
helper class for the creation of MIME messages. It offers support for images, typical mail attachments and text content in an HTML layout
-
In the following sections, we show how these interfaces and classes are used
Spring Mail Server Properties
Mail properties that are needed to specify e.g. the SMTP server may be defined using the JavaMailSenderImpl.
@Bean
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("my.gmail@gmail.com");
mailSender.setPassword("password");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
Spring Boot Mail Server Properties
Once the dependency is in place, the next step is to specify the mail server properties in the application.properties file using the spring.mail.* namespace.
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<login user to smtp server>
spring.mail.password=<login password to smtp server>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Some SMTP servers require a TLS connection, so the property spring.mail.properties.mail.smtp.starttls.enable is used to enable a TLS-protected connection.
Gmail SMTP Properties
We can send an email via Gmail SMTP server. Have a look at the documentation to see the Gmail outgoing mail SMTP server properties.
Our application.the properties file is already configured to use Gmail SMTP (see the previous section).
Note that the password for your account should not be an ordinary password, but an application password generated for your google account. Follow this link to see the details and to generate your Google App Password.
spring.mail.host=localhost
spring.mail.port=25
spring.mail.username=<your user id>
spring.mail.password=<your password>
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false
Sending Email
Once dependency management and configuration are in place, we can use the aforementioned JavaMailSender to send an email.
Since both the plain vanilla Spring framework as well as the Boot version of it handle the composing and sending of e-mails in a similar way, we won’t have to distinguish between the two in the subsections below.
Sending Simple Emails
@Component
public class EmailServiceImpl {
@Autowired
public JavaMailSender emailSender;
public void sendSimpleMessage(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
}
}
Finishing
Add a REST controller which accepts to, subject and text and send it using Postman …
Done
For this part of the exercise you are done regarding using the spring-boot-starter-mail
Continuation
Only applicable later during working hours, and … untested by me …
Sending Emails with Attachments
Sometimes Spring’s simple messaging is not enough for our use cases.
For example, we want to send an order confirmation email with an invoice attached.
In this case, we should use a MIME multipart message from JavaMail library instead of SimpleMailMessage.
Spring supports JavaMail messaging with the org.springframework.mail.javamail.MimeMessageHelper class.
@Override
public void sendMessageWithAttachment(
String to, String subject, String text, String pathToAttachment) {
// ...
MimeMessage message = emailSender.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("Invoice", file);
emailSender.send(message);
// ...
}
Simple Email Template
SimpleMailMessage class supports text formatting. We can create a template for emails by …
@Bean
public SimpleMailMessage templateSimpleMessage() {
SimpleMailMessage message = new SimpleMailMessage();
message.setText(
"This is the test email template for your email:\n%s\n");
return message;
}
@Autowired
public SimpleMailMessage template;
...
String text = String.format(template.getText(), templateArgs);
sendSimpleMessage(to, subject, text);
...
Handling Send Errors
JavaMail provides SendFailedException to handle situations when a message cannot be sent. But it is possible that you won’t get this exception while sending an email to the incorrect address. The reason is the following:
The protocol specs for SMTP in RFC 821 specifies the 550 return code that SMTP server should return when attempting to send an email to the incorrect address. But most of the public SMTP servers don’t do this. Instead, they send a “delivery failed” email to your box, or give no feedback at all.
For example, Gmail SMTP server sends a “delivery failed” message. And you get no exceptions in your program.
-
Catch the SendFailedException, which can never be thrown
-
Check your sender mailbox on “delivery failed” message for some period of time. This is not straightforward and the time period is not determined
-
If your mail server gives no feedback at all, you can do nothing
Conclusion
In this quick article, we showed how to set up and send emails from a Spring Boot application.
The implementation of all these examples and code snippets can be found in the GitHub project; this is a Maven-based project, so it should be easy to import and run as it is.