仿牛客网社区项目(三)发送邮件
发送邮件
-
邮箱设置
- 启用客户端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);
}
}
分类:
仿牛客网社区项目
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署