Spring Boot 配置邮件服务只需三步:添加 spring-boot-starter-mail 依赖、开启邮箱 SMTP 并获取授权码(非登录密码)、在 application.yml 中正确配置 host/port/username/password 及 SSL 参数;验证时优先排查 AuthenticationFailedException。

Spring Boot 配置邮件发送服务,核心就三步:加依赖、开邮箱 SMTP、写配置。关键不是填对参数,而是用对“授权码”而不是登录密码——这点踩坑最多。
添加 spring-boot-starter-mail 依赖
在 pom.xml 中加入:
org.springframework.boot spring-boot-starter-mail
建议顺手加上 spring-boot-starter-web(方便写接口测试)和 lombok(简化实体和日志)。
开启邮箱 SMTP 并获取授权码
登录你要用的邮箱(QQ / 163 / Gmail 等),按路径操作:
- QQ邮箱:设置 → 账户 → 开启 “POP3/IMAP/SMTP 服务” → 发短信验证 → 获取 16 位授权码
- 163邮箱:设置 → POP3/SMTP/IMAP → 开启 SMTP 服务 → 获取授权码
- Gmail:Google 账号 → 安全 → 两步验证开启后 → “应用专用密码” → 生成 16 位密码
⚠️ 记住:这里填的 不是邮箱登录密码,是生成的授权码或应用专用密码。
在调试 Java 后端 API 故障时使用此技能,尤其适用于以下任务:分析日志、跨 Controller、Service 和 Mapper 层追踪请求、定位异常根因、检查 SQL 执行或参数流转,以及生成简洁的诊断结论与修复方案。
application.yml 配置 SMTP 参数
以 QQ 邮箱为例(SSL 端口 465):
spring:mail:host: smtp.qq.comport: 465username: your_email@qq.compassword: your_authorization_codedefault-encoding: UTF-8properties:mail:smtp:auth: truessl:enable: truetrust: smtp.qq.com
如果是 163 或 Gmail,只需改 host、port 和对应授权方式(Gmail 推荐用 starttls.enable: true + 端口 587)。
验证是否生效
写一个简单 Service 测试发送:
- 注入
JavaMailSender - 用
SimpleMailMessage设置收件人、主题、正文 - 调用
mailSender.send()
启动项目,调用一次,查收件箱。如果没收到,优先检查日志里有没有 AuthenticationFailedException —— 大概率是授权码错了或 SMTP 没开。










