1.pom引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置文件配置
#发件人邮箱服务器相关配置
spring.mail.host=smtp.qq.com
spring.mail.port=587
#配置个人QQ账号和密码(密码是加密后的授权码)
spring.mail.username=995536807@qq.com
spring.mail.password=输入你自己的授权码,不会的在下面获取。
spring.mail.default-encoding=UTF-8
#邮件服务超时时间配置
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
3.写好邮件发送业务
package com.example.chapter09.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
@Service
public class SendEmailService {
@Autowired
private JavaMailSenderImpl mailSender;
@Value("${spring.mail.username}") //从配置文件中读取属性值赋给from
private String from;
public void sendSimpleEmail(String to, String subject, String text) {
//定制纯文本邮件信息SimpleMailMessage
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); //发件人地址
message.setTo(to); //收件人地址
message.setSubject(subject); //邮件标题
message.setText(text); //邮件内容
try {
//发送邮件
mailSender.send(message);
System.out.println("纯文本邮件发送成功");
} catch (MailException e) {
System.out.println("纯文本邮件发送失败" + e.getMessage());
e.printStackTrace();
}
}
}
补充:获取QQ授权码。
![]()