在企业应用中,邮件通知是一个常见的功能,比如验证码发送、系统通知、注册确认等。本文将手把手教你如何使用 Spring Boot 整合 网易 163 邮箱 SMTP 服务,实现发送简单邮件。
一、开启 163 邮箱的 SMTP 服务
- 登录 网易 163 邮箱;
- 点击右上角「设置」 → 「账户」 → 找到 POP3/SMTP/IMAP;
- 开启 SMTP服务,系统会弹出一个授权码;
- 复制授权码备用(发送邮件时就是用这个授权码,而不是登录密码);
二、引入 Spring Boot 邮件依赖
在 pom.xml
中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
三、配置邮件服务
你可以选择使用 application.yml
或 application.properties
来配置邮箱信息。
✅ application.yml 示例:
spring:
mail:
host: smtp.163.com
port: 465
username: your_email@163.com
password: your_authorization_code
protocol: smtps
default-encoding: UTF-8
properties:
mail:
smtp:
ssl:
enable: true
✅ application.properties 示例:
spring.mail.host=smtp.163.com
spring.mail.port=465
spring.mail.username=your_email@163.com
spring.mail.password=your_authorization_code
spring.mail.protocol=smtps
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.ssl.enable=true
四、编写邮件发送服务类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("your_email@163.com");
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
}
五、创建一个测试接口
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/mail")
public class MailController {
@Autowired
private MailService mailService;
@GetMapping("/send")
public String sendMail() {
mailService.sendSimpleMail("target@example.com", "测试邮件", "你好,这是来自 Spring Boot 的测试邮件!");
return "邮件发送成功";
}
}
六、常见问题排查
问题 | 可能原因 |
---|---|
535 Error: authentication failed |
使用了邮箱登录密码,而不是授权码 |
Connect timed out |
未开启 SMTP 或端口/SSL 配置错误 |
邮件乱码 | 未设置正确编码(应为 UTF-8) |
✅ 总结
本文介绍了如何快速通过 Spring Boot 集成 163 邮箱服务实现邮件发送功能。实际开发中,你还可以扩展:
- 发送 HTML 邮件
- 邮件模板(如 Thymeleaf)
- 附件邮件、群发邮件