Home > Java > javaTutorial > body text

Example of how to use JavaMailSender to send emails in Spring Boot (source code attached)

黄舟
Release: 2017-03-09 10:10:20
Original
1906 people have browsed it

This article mainly introduces examples of how to use JavaMailSender to send emails in Spring Boot. I believe that many developers who have used Spring know that Spring provides a very easy-to-use JavaMailSender interface to send emails. Automatic configuration is also provided in Spring Boot's Starter module. Friends in need can refer to it.

Quick Start

Introduce the spring-boot-starter-mail dependency into pom.xml in the Spring Boot project:

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

Like other automated configuration modules, after completing the dependency introduction, you only need to configure it in application.properties The corresponding attribute content.

Let’s take QQ mailbox as an example and add the following configuration to application.properties (note to replace your username and password):

spring.mail.host=smtp.qq.com
spring.mail.username=用户名
spring.mail.password=密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
Copy after login

Use unit testing 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("主题:简单邮件");
 message.setText("测试邮件内容");
 mailSender.send(message);
 }
}
Copy after login

Here, a simple The email sending is complete. Run the unit test and see what the effect is?

"Since Spring Boot's starter module provides automated configuration, after introducing the spring-boot-starter-mail dependency, a JavaMailSender instance will be created based on the content in the configuration file, so we can directly configure it when needed Use @Autowired directly to introduce the mail sending object. ”

Advanced use

In the above example, we implement it by using SimpleMailMessage. It is used for simple email sending, but in actual use, we may also bring attachments, or use the email module, etc. At this time we need to use MimeMessage to set more complex email content. Let's implement it in sequence.

Send attachment

Add the following test case to the above unit test (send an email with an attachment through 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("主题:有附件");
 helper.setText("有附件的邮件");
 FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
 helper.addAttachment("附件-1.jpg", file);
 helper.addAttachment("附件-2.jpg", file);
 mailSender.send(mimeMessage);
}
Copy after login

Embed static resources

In addition to sending attachments, we may want to embed static resources such as pictures in the email content to make the email obtain For a better reading experience, instead of viewing specific images from attachments, the following test case demonstrates how to embed static resources in the email body through 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("主题:嵌入静态资源");
 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);
}
Copy after login

What needs to be noted here is that the resource name weixin in the addInline function needs to correspond to the cid:weixin in the text

Template email

Usually when we use email sending services, there will be some fixed scenarios, such as password reset, registration confirmation, etc., and only a small part of the content sent to each user may change. Therefore, many times we will use a template engine to set templates for various types of emails, so that we only need to replace the changed parameters when sending.

It is also very easy to use the template engine in Spring Boot to implement templated email sending. Let’s take Velocity as an example to implement it.

Introduce the dependencies of the velocity module:

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

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

<html>
<body>
 <h3>你好, ${username}, 这是一封模板邮件!</h3>
</body>
</html>
Copy after login

When we developed web applications in Spring Boot before, we mentioned that under the automated configuration of Spring Boot, templates are located in the resources/templates/ directory by default

Finally, we add a test case for sending template emails 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("主题:模板邮件");
 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);
}
Copy after login

Try running it, and you will receive the content for you Okay, didi, this is a template email! Email. Here, we replace the ${username} variable in the template in the email content by passing in the username parameter.


The above is the detailed content of Example of how to use JavaMailSender to send emails in Spring Boot (source code attached). For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!