spring boot 发送邮件
在实际的业务中尤其是一些监控报警的模块中是免不了有各种提醒的,最常见的就是报警邮件功能,Spring框架提供了一个简单的抽象,用于使用该JavaMailSender接口发送电子邮件, 并且Spring Boot为其提供自动配置以及启动器模块。
简介:org.springframework。邮件包的根级别的包是Spring框架的电子邮件支持。中央接口发送邮件是MailSender接口
一个简单的值对象封装的属性一个简单的邮件如和(+其他)是SimpleMailMessage类
这个包还包含一个受控异常层次结构提供更高层次的抽象在低水平根异常是MailException邮件系统异常
org.springframework.mail.javamail。JavaMailSender界面添加专业JavaMail特性如MIME消息支持MailSender接口(继承)
JavaMailSender还提供了制备JavaMail MIME消息的回调接口,称为org.springframework.mail.javamail.MimeMessagePreparator
1.使用前的准备工作
1.1 pom文件的依赖引入:
例子中采用了模版生成正文的情况,故此需要引入另一个依赖,thymeleaf模版引擎(具体使用参考我的另一篇文章)
1.2 配置文件的基本配置
2. 具体实现代码:(文本发送、带有静态资源(如图片)、带有附件、利用模版生成邮件内容、html格式等)
2.1 email的实现类
package com.zxl.examples.email;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* Created by Administrator on 2017/7/26.
*/
@Component("emailService")
public class EmailServiceImpl {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Value("${mail.fromMail.addr}")
private String from;
/**
* 发送文本邮件
* @param to
* @param subject
* @param content
*/
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
logger.info("简单邮件已经发送。");
} catch (Exception e) {
logger.error("发送简单邮件时发生异常!", e);
}
}
/**
* 发送html邮件
* @param to
* @param subject
* @param content
*/
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
logger.info("html邮件发送成功");
} catch (MessagingException e) {
logger.error("发送html邮件时发生异常!", e);
}
}
/**
* 发送带附件的邮件
* @param to
* @param subject
* @param content
* @param filePath
*/
public void sendAttachmentsMail(String to, String subject, String content, String filePath){
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
//helper.addAttachment("test"+fileName, file);
mailSender.send(message);
logger.info("带附件的邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送带附件的邮件时发生异常!", e);
}
}
/**
* 发送正文中有静态资源(图片)的邮件
* @param to
* @param subject
* @param content ""
* @param rscPath
* @param rscId identifier1234
*/
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
MimeMessage message = mailSender.createMimeMessage();
/**
*
* String rscId = "zxl001";
String content="this is a imgage:
2.2 email的调用类,这里采用的controller方式调用
package com.zxl.examples.controller;
import com.zxl.examples.email.EmailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
/**
* Created by Administrator on 2017/7/26.
*/
@RestController
public class EmailController {
@Autowired
EmailServiceImpl emailService;
@Autowired
private TemplateEngine templateEngine;
@GetMapping("/email/sendSimpleMail")
public void sendSimpleMail(){
emailService.sendSimpleMail("zhangxiaolong@weimingedu.com","title","this is a simple email for test.");
}
@GetMapping("/email/sendHtmlMail")
public void sendHtmlMail(){
String content="\n" +
"\n" +
" this is a simple email for test.
\n" +
"\n" +
"";
emailService.sendHtmlMail("zhangxiaolong@weimingedu.com","title",content);
}
@GetMapping("/email/sendAttachmentsMail")
public void sendAttachmentsMail(){
emailService.sendAttachmentsMail("zhangxiaolong@weimingedu.com","title","this is a have attachments email for test.","d:\\桌面.jpg");
}
@GetMapping("/email/sendInlineResourceMail")
public void sendInlineResourceMail(){
String rscId = "zxl001";
String content="this is a imgage:
2.3 email正文的模版
Title
this is a email template,
百度
小提示:1.特别地,某些默认超时值是无限的,您可能需要更改,以避免线程被无响应的邮件服务器阻塞:
spring.mail.properties.mail.smtp.connectiontimeout = 5000
spring.mail.properties.mail.smtp.timeout = 3000
spring.mail.properties.mail.smtp.writetimeout = 5000
2.发送带有内联的静态资源的邮件时有两个地方需要做到一一对应,如下图:
![](https://img-blog.csdn.net/20170801212848281?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbG9uZzI5MDA0NjQ2NA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
参考资料:http://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/htmlsingle/#mail