SpringBoot集成QQ邮箱发送邮件

303 字
2 分钟
SpringBoot集成QQ邮箱发送邮件

1.导入依赖#

<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.6</version>
</dependency>

2.获取QQ邮箱16位SMTP口令#

拉到此处(下图所示)

image.png
image.png
如果是关闭的 请开启 然后就可以得到 16位SMTP

3.添加发送邮件的类(所有导包都是javax.mail下的包)#

public void sendEmail(String email){
//创建Properties类 用于记录邮箱的一些属性
Properties props = new Properties();
//表示SMTP发送邮件 必须进行身份验证
props.put("mail.smtp.auth","true");
//此处填写SMTP服务器
props.put("mail.smtp.host","smtp.qq.com");
//端口号 QQ端口号 587
props.put("mail.smtp.port","587");
//此处填写写信人账号
props.put("mail.user","写信人账号");
//此处填写16位SMTP口令
props.put("mail.password","16位SMTP口令");
//构建授权信息 用于SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//用户名密码
String username = (String) props.get("mail.user");
String password = (String) props.get("mail.password");
return new PasswordAuthentication(username,password);
}
};
//使用环境属性和授权信息 创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
//创建邮件消息
MimeMessage mimeMessage = new MimeMessage(mailSession);
//设置发件人
InternetAddress form = null;
try {
form = new InternetAddress(props.get("mail.user").toString());
mimeMessage.setFrom(form);
InternetAddress to = new InternetAddress(email);
mimeMessage.setRecipients(Message.RecipientType.TO, String.valueOf(to));
//设置邮件标题
mimeMessage.setSubject("标题");
//设置邮件内容体
String content = "内容"
mimeMessage.setContent(content,"text/html;charset=UTF8");
//发送邮件
Transport.send(mimeMessage);
redisTemplate.opsForValue().set(email,code,15L,TimeUnit.MINUTES);
} catch (MessagingException e) {
e.printStackTrace();
}
}

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

SpringBoot集成QQ邮箱发送邮件
https://czxcly.cn/posts/springboot集成qq邮箱发送邮件/
作者
启源学社
发布于
2021-12-10
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
启源学社
公告
欢迎来到我的博客!
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
45
分类
2
标签
16
总字数
16,178
运行时长
0
最后活动
0 天前

文章目录