Spring Boot 使用网易企业邮箱发送邮件:SMTP、TLS 与授权码配置
· 阅读需 1 分钟
网易企业邮箱 SMTP: smtphz.qiye.163.com 25(不加密) 994(加密) 企业邮箱的 SMTP 主机、端口和认证策略可能由管理员调整。配置时应使用环境变量或密钥服务保存凭据,禁止把真实密码提交到 Git 仓库。
spring boot配置
spring:
mail:
host: smtphz.qiye.163.com
port: 994
username: xxxxxx
password: xxxxxx
properties:
"mail.smtp.auth": true
"mail.smtp.ssl.enable": true
"mail.smtp.starttls.enable": false
"mail.smtp.starttls.required": false
"mail.debug": true
发送邮件代码
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
String to = "xxx@example.com";
String code = "1234";
MimeMessage message = mailSender.createMimeMessage();
try {
message.setFrom(new InternetAddress(from));
message.setRecipients(MimeMessage.RecipientType.TO, to);
final String subject = "Verification\u00A0Code";
final String html = "<p>Your verification code is :</p>" +
"<h1>${code}</h1>" +
"<p>Please enter it within 5 minutes.</p>";
message.setSubject(subject);
message.setContent(html.replace("${code}", code), "text/html; charset=utf-8");
} catch (MessagingException e) {
throw new ApiException(500, "send mail failed.");
}
mailSender.send(message);
备注: 阿里云不允许25端口发送邮件