Spring Boot Example of sending mail using JavaMailSender (with source code)

  • 2020-06-07 04:25:48
  • OfStack

Quick start

The spring-ES8en-ES9en-ES10en dependency is introduced in pom.xml in the engineering of Spring Boot:


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

As with other automated configuration module 1, after dependency introduction is completed, only the application.properties The corresponding property content is configured in.

Let's take QQ mailbox as an example application.properties Add the following configuration (take care to replace your username and password) :


spring.mail.host=smtp.qq.com
spring.mail.username= The user name 
spring.mail.password= password 
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

The unit test is used to send a simple email:


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
 @Autowired
 private JavaMailSender mailSender;
 @Test
 public void sendSimpleMail() throws Exception {
 SimpleMailMessage message = new SimpleMailMessage();
 message.setFrom("dyc87112@qq.com");
 message.setTo("dyc87112@qq.com");
 message.setSubject(" Subject: Simple email ");
 message.setText(" Test email content ");
 mailSender.send(message);
 }
}

At this point, a simple email is done. Run the unit test to see how it works.

"Since the starter module of Spring Boot provides automated configuration, after introducing the ES30en-ES31en-ES32en-ES33en dependency, instances of JavaMailSender are created based on the contents of the configuration file, so we can introduce email sending objects directly at @Autowired where we need them."

Use the advanced

In the above example, we implemented simple mail delivery using SimpleMailMessage, but in practice we might also bring attachments, use mail modules, etc. At this time, we need to use MimeMessage to set up more complex 1 email content, let's implement 1 in turn.

Send attachments

Add the following test case to the above unit test (send 1 email with attachment via MimeMessageHelper) :


@Test
public void sendAttachmentsMail() throws Exception {
 MimeMessage mimeMessage = mailSender.createMimeMessage();
 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
 helper.setFrom("dyc87112@qq.com");
 helper.setTo("dyc87112@qq.com");
 helper.setSubject(" Subject: Attached ");
 helper.setText(" There is an attached email ");
 FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
 helper.addAttachment(" The attachment -1.jpg", file);
 helper.addAttachment(" The attachment -2.jpg", file);
 mailSender.send(mimeMessage);
}

Embedded static resource

In addition to sending attachments, we might want to embed static resources such as images in the message content, rather than viewing specific images from attachments. The following test case demonstrates how to embed static resources in the body of the message via MimeMessageHelper.


@Test
public void sendInlineMail() throws Exception {
 MimeMessage mimeMessage = mailSender.createMimeMessage();
 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
 helper.setFrom("dyc87112@qq.com");
 helper.setTo("dyc87112@qq.com");
 helper.setSubject(" Topic: Embed static resources ");
 helper.setText("<html><body><img src=\"cid:weixin\" ></body></html>", true);
 FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
 helper.addInline("weixin", file);
 mailSender.send(mimeMessage);
}

Note here that the resource name weixin in the addInline function needs to correspond to cid:weixin in the body

Template mail

When we use email delivery services, we usually have some fixed scenarios, such as password reset, registration confirmation, etc. Only a small part of the content sent to each user may be changed. So, a lot of times we use a template engine to set up a template for each type of message so that we only need to replace the parameters that change when we send it.

It is also very easy to use the template engine in Spring Boot to implement template-based mail delivery. Let's take velocity as an example for implementation 1.

Introduction of velocity module dependencies:


<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-velocity</artifactId>
</dependency>

Under resources/templates/, create 1 template page template. vm:


<html>
<body>
 <h3> hello  ${username},  This is a 1 Template mail !</h3>
</body>
</html>

When we developed the Web application in Spring Boot, we mentioned that under the automatic configuration of Spring Boot, the template is located in the resources/templates/ directory by default

Finally, we added the test case of sending template mail to the unit test, as follows:


@Test
public void sendTemplateMail() throws Exception {
 MimeMessage mimeMessage = mailSender.createMimeMessage();
 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
 helper.setFrom("dyc87112@qq.com");
 helper.setTo("dyc87112@qq.com");
 helper.setSubject(" Subject: Template mail ");
 Map<String, Object> model = new HashedMap();
 model.put("username", "didi");
 String text = VelocityEngineUtils.mergeTemplateIntoString(
 velocityEngine, "template.vm", "UTF-8", model);
 helper.setText(text, true);
 mailSender.send(mimeMessage);
}

Try running 1 and you will receive hello didi, this is a template email! In the mail. Here, we replace the template in the message content by passing in the arguments to username ${username} The variable.

Complete example: Chapter4-5-1

conclusion

The above is the whole content of this article, I hope the content of this article can bring 1 definite help to your study or work, if you have any questions, you can leave a message to communicate.


Related articles: