1.引入spring-boot-starter-mail依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.application.yml中写入邮箱的基本配置
根据自己的信息填写相应的配置,我这里用的是163邮箱,开通pop3服务后就有授权码了
spring:
mail:
#smtp服务主机
host: smtp.163.com
#服务协议
protocol: smtp
# 编码集
default-encoding: UTF-8
#发送邮件的账户
username: ****@163.com
#授权码
password: ******
test-connection: true
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
至此,邮箱的配置已完成.
3.创建邮箱实体类
这里使用一个简洁的实体类(包含收件人列表,邮件主题,邮件内容),使用lombok简化开发
@Data
public class Email {
private String[] user;
private String subject;
private String content;
}
4.发送邮件实现代码
创建一个Service类,注入JavaMailSender类型的对象,这个对象含有邮件发送的的方法send,之后通过@Value读取yml文件中的发邮件人的账号,创建SimpleMailMessage对象,并设置一系列发送邮件必要的参数.
@Service
public class EmailService {
@Resource
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String senderName;
public void sendMail(Email email){
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(senderName);
// 邮件接收人
mailMessage.setTo(email.getUser());
// 邮件主题
mailMessage.setSubject(email.getSubject());
// 邮件内容
mailMessage.setText(email.getContent());
mailSender.send(mailMessage);
}
}
5.编写controller测试
注入EmailService,set方法写入测试数据
@RestController
public class EmailController {
@Autowired
EmailService emailService;
@GetMapping("/testsendmail")
public void toMail(){
Email email = new Email();
email.setUser(new String[]{"####@163.com"});
email.setSubject("测试");
email.setContent("hello.this is my email demo");
emailService.sendMail(email);
}
}