SpringBoot中集成常见邮箱中容易出现的问题
本来也没打算想写得。不过也是遇到一些坑,就记录一下吧,也折腾了小半天
1.maven配置
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
2.实例代码
代码比较简单,如下就是
/*** @description:邮件服务* @author:hutao* @mail:hutao1@epri.sgcc.com.cn* @date:2024年12月10日 上午10:59:20*/
@Service
public class EmailServiceImpl implements EmailService{@Resourceprivate JavaMailSender mailSender;@Value("${spring.mail.username}")private String from;@Overridepublic void sendSimpleEmail(String to, String subject, String text) {SimpleMailMessage message = new SimpleMailMessage();message.setFrom(from);message.setTo(to);message.setSubject(subject);message.setText(text);mailSender.send(message);}
}
3.各邮箱配置
3.1.个人qq邮箱
以下是我验证测试以后可用的配置,如果需要,复制得时候,更改username和password即可
spring:#邮箱配置mail:host: smtp.qq.comprotocol: smtpsport: 465username: 123456@qq.com#这里是授权码,不是邮箱密码password: opzamrrkjfxtbcbidefault-encoding: utf-8properties:mail:smtp:auth: truestarttls:enable: truerequired: true
3.1.1.常见问题:AuthenticationFailedException
QQ邮箱如下报错,password错误需要用授权码,而不是密码。
AuthenticationFailedException: 535 Login Fail. Please enter your authorization code to login.
More information in https://service.mail.qq.com/detail/0/53
登录qq邮箱,在安全设置中,生成授权码(需要用手机发短信),得到一串随机字符串,密码就是这串字符串。
如果生成授权码失败,提示请稍后在试,请在帐号设置中,检查下邮箱是否已经绑定了手机。
3.1.2.常见问题:Got bad greeting from SMTP
调用发送以后,等到一会儿,报错
Got bad greeting from SMTP host: smtp.qq.com, port: 465, response: [EOF]
如果你和我一样:在cmd中,使用:telnet smtp.qq.com 465,一样没问题的话,则检查下配置查看配置中是否包含:protocol
3.2.阿里云个人邮箱
以下是我验证测试以后可用的配置,如果需要,复制得时候,更改username和password即可
spring:mail:#阿里云邮箱配置host: smtp.aliyun.comprotocol: smtpsport: 465username: hutao_2017@aliyun.com#个人邮箱这里是邮箱密码,不是授权码,如果是阿里外贸邮,则是授权码password: xxaabbccdefault-encoding: utf-8properties:mail:smtp:auth: truestarttls:enable: truerequired: true
3.2.1.常见问题:AuthenticationFailedException
AuthenticationFailedException: 526 Authentication failure[0]
密码错误,注意检查下需要密码还是授权码,别用错了导致密码错误,这里需要注意,普通的个人阿里云邮箱,用邮箱密码就可以,是不需要授权码,我在官网找了很久,也没找到授权码,但是,如果你用的不是普通阿里云邮箱,比如是外贸阿里云邮箱,则需要你使用授权码。
这是普通的阿里云账户安全页面,可以看到,是没有授权码的
如果是阿里外贸邮箱,则是有授权码(三方客户端安全密码)
3.2.2.常见问题:Got bad greeting from SMTP
同上面的个人QQ邮箱一样处理思路
3.3.网易个人邮箱
spring:mail:#网易邮箱配置host: smtp.163.comprotocol: smtpsport: 465username: hutao_2017@163.com#这里是授权码,不是帐号密码password: 1111111111default-encoding: utf-8properties:mail:smtp:auth: truestarttls:enable: truerequired: true
3.3.1.常见问题:AuthenticationFailedException
AuthenticationFailedException: 535 Error: authentication failed
网易邮箱需要用授权码登录
3.2.2.常见问题:Got bad greeting from SMTP
同上面的个人QQ邮箱一样处理思路