Last Updated on 25 July 2022   |   Print Email
In this tutorial, I would like to share with you some code examples for sending emails in a Spring Boot application, from sending a plain text email to an HTML email with inline images. Then you will be able to implement email sending functions in Java applications based on Spring framework, such as sending user registration verification email, sending One-Time Password (OTP) email, sending order confirmation email, etc.
1. Declare Dependency for Spring Boot Mail
Spring Boot Starter Mail is a thin wrapper around Jakarta Mail (the new name of JavaMail), which makes it easier to integrate emailing functionality into Spring-based applications. So declare the following dependency in the Maven project file:
In order to send email from your application, you need to configure SMTP server settings in the Spring Boot application configuration file (application.properties) as follows:
This is the configuration for using GMail’s SMTP server with connection encrypted (using TLS). Of course you can use settings of your own SMTP server. In case you use GMail, you must enable SMTP in your GMail account settings and generate an access password (not your email password) for better security.
3. Configure a JavaMailSender
Spring Mail provides JavaMailSender which is the key interface that defines common methods for sending emails. After configuring mail properties in the application.properties file, you can tell Spring framework to inject the default implementation of JavaMailSender into a Spring MVC controller class like this:
@Controller
public class AppController {
@Autowired
private JavaMailSender mailSender;
public void sendEmail() {
// use mailSender here...
}
}
Also in a business/service class:
@Service
public class BusinessService {
@Autowired
private JavaMailSender mailSender;
public void sendEmail() {
// use mailSender here...
}
}
Or in any Spring-managed component as follows:
@Component
public class BusinessComponent {
@Autowired
private JavaMailSender mailSender;
public void sendEmail() {
// use mailSender here...
}
}
In a non-Spring environment (e.g. in a JUnit test), you must create a new instance of JavaMailSenderImpl – the default implementation of JavaMailSender like this:
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("your_email");
mailSender.setPassword("your_password");
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
mailSender.setJavaMailProperties(properties);
So you can see, in a Spring Boot application, you just need to declare the mail properties and then you’re ready to use the JavaMailSender.
4. Code Example for Sending Simple Email (Plain Text)
The code snippet below demonstrates how to send a plain text email:
String from = "sender@gmail.com";
String to = "recipient@gmail.com";
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject("This is a plain text email");
message.setText("Hello guys! This is a plain text email.");
mailSender.send(message);
You see, the code is simple and self-explanatory. The send() method may throw MailException which is a runtime exception in case of error – so you can decide to catch this exception or not. And this is how the email looks like in GMail:
5. Code Example for Sending HTML Email
And the following code example shows you how to send an email in HTML format:
String from = "sender@gmail.com";
String to = "recipient@gmail.com";
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setSubject("This is an HTML email");
helper.setFrom(from);
helper.setTo(to);
boolean html = true;
helper.setText("<b>Hey guys</b>,<br><i>Welcome to my new home</i>", html);
mailSender.send(message);
You see, you can embed HTML tags directly into the body text of the email message. And below is how the email looks like in GMail:
6. Code Example for Sending Email with Attachment
It’s also simple to send an HTML with an attachment, as shown in the code example below:
String from = "sender@gmail.com";
String to = "recipient@gmail.com";
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject("Here's your e-book");
helper.setFrom(from);
helper.setTo(to);
helper.setText("<b>Dear friend</b>,<br><i>Please find the book attached.</i>", true);
FileSystemResource file = new FileSystemResource(new File("Book.pdf"));
helper.addAttachment("FreelanceSuccess.pdf", file);
mailSender.send(message);
As you can see, the code reads a PDF file from file system and attach it into the outgoing email. Below is how the email looks like in GMail:
7. Code Example for Sending Email with Inline Images
You can also inline a picture right inside the email content, as shown in the following code example:
String from = "sender@gmail.com";
String to = "recipient@gmail.com";
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject("Here's your pic");
helper.setFrom(from);
helper.setTo(to);
String content = "<b>Dear guru</b>,<br><i>Please look at this nice picture:.</i>"
+ "<br><img src='cid:image001'/><br><b>Best Regards</b>";
helper.setText(content, true);
FileSystemResource resource = new FileSystemResource(new File("picture.png"));
helper.addInline("image001", resource);
mailSender.send(message);
Note that you must specify cid value for the image tag, where a picture will be embedded to. And here’s how the email looks like in GMail:Those are common code examples for sending emails in a Spring Boot application. I hope you’ve found this article helpful. To see the coding in action, I recommend you to watch the following video:You can also download the sample project in the Attachments section below, or clone code from GitHub.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Hi aymen: can you share the source saying that Gmail is not working with Spring mail? Spring Mail is a wrapper of JavaMail which can work with any SMTP server including GMail.
Comments
tôi rất thích