仿牛客网社区项目(三)发送邮件
发送邮件
-
邮箱设置
- 启用客户端SMTP服务
-
Spring Email
- 导入 jar 包
- 邮箱参数配置
- 使用 JavaMailSender 发送邮件
-
模板引擎
- 使用 Thymeleaf 发送 HTML 邮件
1.前置服务
开启邮箱pop3/SMTP服务
①导入相关jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.3.7.RELEASE</version>
</dependency>
②配置相关的邮箱参数
#MailProperties
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=******@qq.com
spring.mail.password=********
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
③使用javaMailSender发送邮件
首先将发送邮件的逻辑封装,以便反复使用,新建一个工具包util,并在包下新建一个工具类MailClient
@Component
public class MailClient {
private static final Logger logger= LoggerFactory.getLogger(MailClient.class);
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
public void sendMail(String to,String subject,String content){
try {
MimeMessage message=mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(message);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
logger.error("发送邮件失败:"+e.getMessage());
}
}
}
在测试类中进行测试发送文本邮件
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;
@Test
public void testTextMail(){
mailClient.sendMail("******@******.edu.cn","TEST","Welcome.");
}
3.模板引擎——使用Thymeleaf发送模板引擎
①在template包下的mail文件夹新建一个模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件示例</title>
</head>
<body>
<p>欢迎你,<span style="color:#ff0000;" th:text="${username}"></span></p>
</body>
</html>
使用模板引擎生成动态网页,再通过MailClient即可完成发送
@SpringBootTest
@ContextConfiguration(classes=CommunityApplication.class)
public class MailTests {
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;
@Test
public void testHtmlMail(){
Context context=new Context();
context.setVariable("username","sunday");
String content=templateEngine.process("mail/demo",context);
System.out.println(content);
mailClient.sendMail("*****@*****","HTML",content);
}
}

浙公网安备 33010602011771号