Spring Boot实现发送邮件

注意:这篇博客是自己学完发送邮箱之后的一个小总结,不适合新手拿来学习用!


 

分为三步:

1.邮箱的设置:在你使用的邮箱内启用客户端SMTP服务

2.Spring Email:导入jar包;邮箱参数配置;使用JavaMailSender发送邮件

3.模板引擎:使用Thymeleaf发送HTML邮件

 

1.首先发送邮件需要一个代理发送邮件的邮箱,启用SMTP服务:

改图是使用的新浪邮箱:

 

2.在pom.xml中导入jar包(spring-boot-starter-mail):

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

 

在项目的配置文件中配置代理发送邮件的邮箱属性:

1 spring.mail.host=smtp.sina.com
2 spring.mail.port=465
3 spring.mail.username=#这里填邮箱地址
4 spring.mail.password=#这里填邮箱的授权码5 spring.mail.protocol=smtps
6 spring.mail.properties.mail.smtp.ssl.enable=true

 

然后使用JavaMailSender发送邮件:

 1 import org.slf4j.Logger;
 2 import org.slf4j.LoggerFactory;
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Value;
 5 import org.springframework.mail.javamail.JavaMailSender;
 6 import org.springframework.mail.javamail.MimeMessageHelper;
 7 import org.springframework.stereotype.Component;
 8 
 9 import javax.mail.MessagingException;
10 import javax.mail.internet.MimeMessage;
11 
12 @Component
13 public class MailClient {
14 
15     private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
16 
17     @Autowired
18     private JavaMailSender mailSender;
19 
20     @Value("${spring.mail.username}")
21     private String from;
22 
23     public void sendMail(String to,String subject,String content){
24         try {
25             MimeMessage message = mailSender.createMimeMessage();
26             MimeMessageHelper helper = new MimeMessageHelper(message);
27             helper.setFrom(from);
28             helper.setTo(to);
29             helper.setSubject(subject);
30             helper.setText(content,true);
31             mailSender.send(helper.getMimeMessage());
32         } catch (MessagingException e) {
33             logger.error("发送邮箱失败:"+e.getMessage());
34         }
35 
36     }
37 }

 

这里看JavaMailSender源码就可以发现这个JavaMailSender只做两件事情

创建MimeMessage还有发送邮件,如下代码:

 

 1 public interface JavaMailSender extends MailSender {
 2     MimeMessage createMimeMessage();
 3 
 4     MimeMessage createMimeMessage(InputStream var1) throws MailException;
 5 
 6     void send(MimeMessage var1) throws MailException;
 7 
 8     void send(MimeMessage... var1) throws MailException;
 9 
10     void send(MimeMessagePreparator var1) throws MailException;
11 
12     void send(MimeMessagePreparator... var1) throws MailException;
13 }

 

 

 

使用JavaMailSender创建MimeMessage之后可以使用一个名为MimeMessageHelper的类来set参数,然后用JavaMailSender执行发送方法.

1 MimeMessage message = mailSender.createMimeMessage();
2 MimeMessageHelper helper = new MimeMessageHelper(message);
3 helper.setFrom(from);
4 helper.setTo(to);
5 helper.setSubject(subject);
6 helper.setText(content,true);
7 mailSender.send(helper.getMimeMessage());        

 

3.使用Thymeleaf模板引擎发送HTML格式的邮件

在templates下创建一个html:

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>邮箱示例</title>
 6 </head>
 7 <body>
 8     <p>欢迎你,<span style="color: red" th:text="${username}"></span>!</p>
 9 </body>
10 </html>

 

在测试类中测试:

 1 import com.nowcoder.community.util.MailClient;
 2 import org.junit.Test;
 3 import org.junit.runner.RunWith;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.boot.test.context.SpringBootTest;
 6 import org.springframework.test.context.ContextConfiguration;
 7 import org.springframework.test.context.junit4.SpringRunner;
 8 import org.thymeleaf.TemplateEngine;
 9 import org.thymeleaf.context.Context;
10 
11 
12 @RunWith(SpringRunner.class)
13 @SpringBootTest
14 @ContextConfiguration(classes = CommunityApplication.class)
15 public class MailTests {
16 
17     @Autowired
18     private MailClient mailClient;
19 
20     @Autowired
21     private TemplateEngine templateEngine;
22 
23     @Test
24     public void testHtmlMail(){
25         Context context = new Context();
26         context.setVariable("username","sunday");
27 
28         String content = templateEngine.process("/mail/demo",context);
29         System.out.println(content);
30 
31         mailClient.sendMail("目标邮箱","邮件标题","邮件内容");
32     }
33 }

 

测试之后邮箱就会发送给目标邮箱!

 

posted @ 2020-07-02 16:58  手下留情  阅读(489)  评论(0编辑  收藏  举报