Spring Boot 发送邮件全解析
1.前言
电子邮件虽然近几年有点“退火”,但是在开发中依然有举足轻重的地位。在比较正式的场合我们依然通过电子邮件来传递信息和回执。今天我们就来学一下如何在 Spring Boot 下发送电子邮件。
2. 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3. Service
@Service
public class EmailService {
@Autowired
private JavaMailSenderImpl javaMailSender;
//简单邮件测试
public void sendSimple(){
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("email测试");
message.setText("邮件测试内容");
message.setTo("xxx@sohu.com");
message.setFrom("xxx@sohu.com");
javaMailSender.send(message);
}
//复杂邮件测试
public void sendComplicated() throws MessagingException {
//创建一个复杂的消息邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//用MimeMessageHelper来包装MimeMessage
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setSubject("email测试");
mimeMessageHelper.setText("邮件测试内容");
mimeMessageHelper.setTo("fanqixxxx@vip.qq.com");
mimeMessageHelper.setFrom("fanqixxxx@163.com");
mimeMessageHelper.addAttachment("meinv.jpg",new File("D:\\meinv.jpg"));
javaMailSender.send(mimeMessage);
}
4. application.properties
spring.mail.username=dddddf@sohu.com
#spring.mail.password 填写授权码
spring.mail.password=ddddd
#spring.mail.host 填写邮箱供应的SMTP地址
spring.mail.host=smtp.sohu.com
spring.mail.properties.mail.smtp.ssl.enable=true