一、开启SMTP服务
二、编码
1、加依赖(pom.xml)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、写配置(application.properties)
##mail
spring.mail.host=smtp.qq.com
spring.mail.username=自己的邮箱@qq.com
spring.mail.password= 邮箱授权码
#spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.qq.com
spring.mail.properties.mail.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.port=465
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
三、发送邮件
1、发送html邮件
@RestController
public class MailController {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private MailProperties mailProperties;
@GetMapping("/html")
public String html() throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message);
messageHelper.setFrom(this.mailProperties.getUsername());
messageHelper.setTo("@qq.com");
messageHelper.setSubject("HTML内容邮件测试");
// 第二个参数表示是否html,设为true
messageHelper.setText("<h1>HTML内容..</h1>", true);
this.javaMailSender.send(message);
return "success";
}
}
2、发送带附件的邮件
@GetMapping("/attach")
public String attach() throws MessagingException {
MimeMessage message = this.javaMailSender.createMimeMessage();
// 第二个参数表示是否开启multipart模式
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
messageHelper.setFrom(this.mailProperties.getUsername());
messageHelper.setTo("@qq.com");
messageHelper.setSubject("带附件的邮件测试");
// 第二个参数表示是否html,设为true
messageHelper.setText("<h1>HTML内容..</h1>", true);
messageHelper.addAttachment("2b1ae927328f17aab060e2206198b91.jpg",
new File("src/main/resources/2b1ae927328f17aab060e2206198b91.jpg"));
this.javaMailSender.send(message);
return "success";
}
四、效果
注意:
附件路径问题:
1、附件放在resource目录下应src/main/resources/2b1ae927328f17aab060e2206198b91.jpg
2、附件放在其他位置
C:\Users\huo\Desktop\一个文件夹\大二下学期\2b1ae927328f17aab060e2206198b91.jpg