微服务 教程
1085个小节阅读:195.6k
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在用户注册成功后,要向用户的邮箱发送一封激活邮件,发送邮件需要在系统中配置发件人,同学们使用自己的邮箱作为发件人即可。
配置邮箱第三方登录。
我们在系统中使用邮箱发送邮件属于第三方登录,而市面上的邮箱默认是不能第三方登录的。我们需要登录邮箱,配置第三方登录。以QQ邮箱配置举例:
登录QQ邮箱,点击设置——账户:
开启POP3/SMTP服务:
用密保手机向1069070069
发送短信配置邮件客户端
,发送完成后点击我已发送。
记住授权码,该授权码就是配置发件人时的邮箱密码:
在pom中引入发送邮件依赖
xxxxxxxxxx
<!-- 发邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
在yml文件配置发件人用户名密码
xxxxxxxxxx
# 发送邮件配置
mail
# 发件人地址
user 461618768@qq.com
# 发件人密码
password yioaiekdcphnbije
引入邮件发送工具类
xxxxxxxxxx
/**
* 发邮件工具类
*/
public final class MailUtils{
"${mail.user}") (
private String USER; // 发件人邮箱地址
"${mail.password}") (
private String PASSWORD; // 如果是qq邮箱可以使户端授权码
/**
* 发送邮件
* @param to 收件人邮箱
* @param text 邮件正文
* @param title 标题
*/
public boolean sendMail(String to, String text, String title){
try {
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
// 发件人的账号
props.put("mail.user", USER);
//发件人的密码
props.put("mail.password", PASSWORD);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
// 设置收件人
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);
// 设置邮件标题
message.setSubject(title);
// 设置邮件的内容体
message.setContent(text, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
return true;
}catch (Exception e){
e.printStackTrace();
}
return false;
}
}
测试发送邮件方法
xxxxxxxxxx
private MailUtils mailUtils;
void sendMail() {
mailUtils.sendMail("461618768@qq.com","这是一封测试邮件","测试");
}