需要引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
(重要)前期准备:
这里用qq邮箱示例 开通一些权限
第一步:点击设置
==第二步:点击账户=
第三步:开启服务,保存授权码接下来要用
代码体:
try {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
// qq邮箱就是smtp.qq.com 其余邮箱类型自行修改
props.put("mail.smtp.host", "smtp.qq.com");
// 发送者邮箱 格式 xxx@qq.com
props.put("mail.user", "XXX");
// 授权码(刚才开启服务获得的授权码)
props.put("mail.password", "fafinhvzlohkdjha");
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
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);
InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
message.setFrom(form);
// 接收方邮箱 格式 XXX@xx.com
InternetAddress to = new InternetAddress("XXX");
message.setRecipient(MimeMessage.RecipientType.TO, to);
// 抄送的邮箱地址 格式 XXX@xx.com
message.setRecipients(MimeMessage.RecipientType.CC,InternetAddress.parse("xxx"));
// 主题名
message.setSubject("XXX");
// 发送内容
message.setContent("XXX", "text/html;charset=UTF-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
稍微修改一下变量值就能直接使用