本文主要介紹如何使用SpringBoot自帶的spring-boot-starter-mail實(shí)現(xiàn)郵件發(fā)送功能
(支持文本格式郵件、html格式郵件乎完、帶有多附件的郵件砍聊、帶有多資源的郵件)
1. 引入依賴包
在pom.xml中引入spring-boot-starter-mail依賴包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. 配置郵件發(fā)送參數(shù)
在application.properties中加入如下參數(shù):
spring.mail.host=smtp.xxx.com
spring.mail.username=xxx@xxx.com
spring.mail.password=xxxxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
如果是application.yml,如下:
spring:
mail:
host: smtp.xxx.com
username: xxx@xxx.com
password: xxxxxx
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
3. 添加代碼發(fā)送郵件
/**
* 注入MailSender
*/
@Autowired
private JavaMailSender mailSender;
/**
* 讀取配置文件中的發(fā)送用戶信息
*/
@Value("${spring.mail.username}")
private String fromEmail;
發(fā)送文本格式郵件:
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail);
/**
* 收件人郵件地址
*/
message.setTo(toEmail);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
發(fā)送Html格式/帶有多附件/帶有多資源的郵件:
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromEmail);
helper.setTo(toEmail);
helper.setSubject(subject);
helper.setText(mailBody, true);
/**
* 判斷附件是否為空
*/
if(!StringUtils.isEmpty(photos)){
/**
* 多附件處理
*/
photos.entrySet().forEach(entry->{
try {
FileSystemResource file = new FileSystemResource(new File(entry.getValue()));
if(isAttachment) {
helper.addAttachment(entry.getKey(), file);
}else {
helper.addInline(entry.getKey(),file);
}
} catch (MessagingException e) {
e.printStackTrace();
mailSenderModal.setCode(-2);
mailSenderModal.setMsg(e.getMessage());
}
});
}
mailSender.send(message);
源碼參考地址:
https://github.com/futurebox/SpringBoot/tree/master/MailSender