开启服务
开启自己邮箱的SMTP服务
设置 ——> 账户 ——> 开启服务
引入依赖
选用与Spring Boot整合的
org.springframework.boot spring-boot-starter-mail 2.5.5
配置邮箱
分别配置邮箱的 域名/主机、端口、邮箱账号、邮箱密码、发送协议(加密)、发送时采用ssl连接的详细配置
注意:
username为自己的邮箱账号
password为邮箱的授权码
spring.mail.host=smtp.qq.com spring.mail.port=465 spring.mail.username=****** spring.mail.password=****** spring.mail.protocol=smtps spring.mail.properties.mail.smpt.ssl.enable=true
封装发送邮件的实体类,可以重复使用
注意依赖注入值:@Value("${配置文件的key}")
@Component
public class MailClient{
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
public void sendMail(String to, String subject, String context) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
// 支持html文本
helper.setText(context, true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
测试
测试中调用MailClient中的sendMail方法,即可发送成功
实现过程中的问题
- javax.mail.NoSuchProviderException: No provider for smpts
org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.NoSuchProviderException: No provider for smpts. Failed messages: javax.mail.NoSuchProviderException: No provider for smpts
; message exception details (1) are:
Failed message 1:
没有提供smpt
properties文件中的加密协议出错
应为 smtps
- 535 Login Fail.
javax.mail.AuthenticationFailedException: 535 Login Fail. Please enter your authorization code to login. More information in http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
535登录失败
properties文件spring.mail.password值出错,应为授权码
- 502 Invalid input from 118.74.26.137 to newxmesmtplogicsvrsza7.qq.com.
无效的输入,从 from 到 to
是 MailClient 的 String from 依赖注入的值错误
注意取properties文件中的值:${}



