登录QQ邮箱 开启smtp服务
首先登录QQ邮箱 点击设置
在邮箱设置里选择账户
下拉找到如下位置. 开启POP3/SMTP服务
这里可能需要验证手机号 按照提示进行操作即可.
开启成功后 复制好授权码待用. (是连续的没有空格)
创建SpringBoot项目
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
修改SpringBoot配置文件
spring:
mail:
host: smtp.qq.com
port: 465 #端口
username: 123456@qq.com #自己的QQ账号
password: zvylfdpzqhfjecah #密码使用授权码
protocol: smtps #设置邮件协议 smtps
写一个发邮件的客户端
@Component
public class MailClient {
private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
/**
*
* @param to 收件人邮箱地址
* @param subject 邮件主题
* @param content 邮件内容
*/
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);
//邮件内容,运行发送html页面
helper.setText(content, true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
logger.error("发送邮件失败:" + e.getMessage());
}
}
}
/mail/demo.html模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件示例</title>
</head>
<body>
<p>欢迎你, <span style="color:red;" th:text="${username}"></span>!</p>
</body>
</html>
测试
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;
/**
* 简单邮件
*/
@Test
public void testTextMail() {
mailClient. sendMail("520@qq.com", "TEST", "Welcome.");
}
/**
* 发送以HTML为模板的邮件
*/
@Test
public void testHtmlMail() {
Context context = new Context();
//设置传入模板的页面的参数 参数名为:id 参数随便写一个就行
context.setVariable("username", "sunday");
///mail/demo是你要发送的模板我这里用的是Thymeleaf
String content = templateEngine.process("/mail/demo", context);
System.out.println(content);
mailClient.sendMail("520@qq.com", "HTML", content);
}
}