Springboot+Javamail實現(xiàn)郵件發(fā)送
使用的是spring-context-support-5.2.6.RELEASE.jar里的javamail
javamail 官方文檔:javamail
代碼在:gitee
官方代碼介紹
Sample code for an HTML mail with an inline image and a PDF attachment:
帶有圖像和PDF附件的HTML郵件的示例代碼:
mailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setFrom("me@mail.com");
message.setTo("you@mail.com");
message.setSubject("my subject");
message.setText("my text <img src='cid:myLogo'>", true);
message.addInline("myLogo", new ClassPathResource("img/mylogo.gif"));
message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
}
});
MimeMessageHelper參數(shù)說明
- from(發(fā)件人)
- to(收件人)
- subject(郵件主題)
- text(內(nèi)容)
- inline(內(nèi)嵌圖片或者圖片附件)
- attachment(附件)
- cc(抄送人)
- bcc(密送人)
Springboot 代碼示例
開啟POP3/SMTP服務(wù)抽减,并拿到授權(quán)碼
首先登錄163郵箱 開啟POP3/SMTP服務(wù)
拿到授權(quán)碼
application.yml配置文件不要填郵箱密碼允青,要填授權(quán)碼,不然會報錯:535 Error: authentication failed
application.yml配置文件
spring:
mail:
default-encoding: UTF-8
host: smtp.163.com
username: owl_email@163.com
# 不要填郵箱密碼胯甩,要填授權(quán)碼,不然會報錯:535 Error: authentication failed
password:
protocol: smtp
properties:
mail:
smtp:
auth: true
port: 994 #465或者994
starttls:
enable: true
required: true
ssl:
enable: true
display:
sendmail: Javen
sendname: Spring Boot Guide Email
MailDetail(參數(shù)封裝)
記得setter堪嫂、getter
public class MailDetail {
/**
* 發(fā)件人名稱
*/
private String senderName;
/**
* 發(fā)件人郵件地址
*/
private String senderMail;
/**
* 收件人地址
*/
private String addresseeMail;
/**
* 郵件標(biāo)題
*/
private String mailTitle;
/**
* 抄送人
*/
private String[] cc;
/**
* 郵件內(nèi)容
*/
private String content;
/**
* true內(nèi)容為HTML偎箫,false內(nèi)容為文本 默認文本
*/
private Boolean html = false;
}
發(fā)送郵件Service層
@Service
public class MailServiceImpl implements MailService {
private static final Logger log = LoggerFactory.getLogger(MailServiceImpl.class);
private final JavaMailSender javaMailSender;
@Autowired
public MailServiceImpl(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
@Override
public boolean sendMessage(MailDetail detail) {
log.info("mailServiceImpl.sendMessage.request:{}", new Gson().toJson(detail));
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
// 發(fā)件人地址
InternetAddress fromAddress = new InternetAddress(MimeUtility.encodeText(detail.getSenderName()) + "<" + detail.getSenderMail() + ">");
messageHelper.setFrom(fromAddress);
// 收件人地址
InternetAddress toAddress = new InternetAddress(MimeUtility.encodeText(detail.getAddresseeMail()) + "<" + detail.getAddresseeMail() + ">");
messageHelper.setTo(toAddress);
// 郵件名稱
messageHelper.setSubject(detail.getMailTitle());
// 第二個參數(shù)指定發(fā)送的是HTML格式
messageHelper.setText(detail.getContent(), detail.getHtml());
// 抄送人
if (detail.getCc() != null && detail.getCc().length > 0) {
messageHelper.setCc(detail.getCc());
}
// 測試圖片附件(ClassPathResource要把圖片放到resources,并且編譯代碼把圖片加載到target里)
// messageHelper.addInline("myLogo", new ClassPathResource("WechatIMG2602.jpeg"));
javaMailSender.send(message);
return true;
} catch (MessagingException | UnsupportedEncodingException e) {
log.error("mailServiceImpl.sendMessage.error:{},{}", e.getMessage(), e.getStackTrace());
}
return false;
}
}
發(fā)送郵件Controller層
主要controller實現(xiàn)類ApplicationRunner 的run 項目啟動則執(zhí)行
@RestController
public class MailController implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(MailController.class);
protected final MailService mailService;
@Autowired
public MailController(MailService mailService) {
this.mailService = mailService;
}
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("syncController.run");
MailDetail mailDetail = new MailDetail();
// 發(fā)件人名稱
mailDetail.setSenderName("云深小麥");
// 發(fā)件人郵箱
mailDetail.setSenderMail("owl_email@163.com");
// 郵件名稱
mailDetail.setMailTitle("這里是測試");
// 收件人郵箱
mailDetail.setAddresseeMail("guoqingyan_email@163.com");
// 發(fā)送純文本 setHtml(false) 默認false
// mailDetail.setContent("你好皆串!我是云深小麥");
// 發(fā)送HTML setHtml(true)
mailDetail.setContent("<html><head></head><body><h1>你好淹办!我是云深小麥</h1></body></html>");
// 內(nèi)容是否為HTML
mailDetail.setHtml(true);
boolean b = mailService.sendMessage(mailDetail);
if (b) {
log.info("發(fā)送成功");
}
}
}
結(jié)果
一些問題
535 Error: authentication failed
Caused by: javax.mail.AuthenticationFailedException: 535 Error: authentication failed
調(diào)用163郵箱服務(wù)器來發(fā)送郵件,我們需要開啟POP3/SMTP服務(wù),這時163郵件會讓我們設(shè)置客戶端授權(quán)碼,這個授權(quán)碼替代上面代碼部分的passwd即可成功發(fā)送郵件
550 Invalid User
com.sun.mail.smtp.SMTPSenderFailedException: 550 Invalid User
該錯誤表示:收件地址為無效帳號恶复。
建議:
1怜森,請檢查收件人地址是否存在語法錯誤,例如說有攜帶多余的標(biāo)點符號谤牡。地址與地址之間的分隔號是英文字符下的分號副硅。
2,請檢查收件人地址是否有錯誤翅萤,收件人不存在等情況恐疲。
3,請檢查發(fā)件人在系統(tǒng)的狀態(tài)套么,是否被刪除培己、禁用或者凍結(jié)狀態(tài)。