前言
项目中邮件发送为常用功能之一,例如注册成功后需要发送激活邮件,账号的会员到期提示,每日报表统计等功能都需要自动发送邮件,本文将讲解Spring Boot如何实现邮件发送功能。
集成步骤
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
邮件配置信息
在resource目录下新增mail.properties内容如下:
#企业邮件配置
mail.host=smtp.exmail.qq.com
#端口
mail.port=587
mail.userName=xxx.com
mail.password=yyy
mail.smtp.timeou=15000
mail.smtp.auth=false
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
加载属性文件
@Component
@ConfigurationProperties(prefix = "mail")
@PropertySource(value = { "classpath:mail.properties" })
public class MailSenderConfig implements Serializable
{
private static final long serialVersionUID = -4558468113448742143L;
private String host;
private int port;
private String userName;
private String password;
//省略get、set方法
}
通过@PropertySource注解加载外部属性文件,不熟悉的朋友可以查看这篇文章。
邮件配置类
@Configuration
public class MailConfig
{
@Autowired
private MailSenderConfig mailSenderConfig;
@Bean
public JavaMailSenderImpl createMailSender()
{
JavaMailSenderImpl javaMailSender =new JavaMailSenderImpl();
javaMailSender.setDefaultEncoding("UTF-8");
javaMailSender.setHost(mailSenderConfig.getHost());
javaMailSender.setPort(mailSenderConfig.getPort());
javaMailSender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL);
javaMailSender.setUsername(mailSenderConfig.getUserName());
javaMailSender.setPassword(mailSenderConfig.getPassword());
Properties p = new Properties();
p.setProperty("mail.smtp.timeout", "25000");
p.setProperty("mail.smtp.auth", "true");
p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
javaMailSender.setJavaMailProperties(p);
return javaMailSender;
}
}
注意:JavaMailSenderImpl是JavaMailSender的实现。
代码实现
发送简单邮件
邮件实体类
public class Mail implements Serializable
{
private static final long serialVersionUID = -1001194001681838276L;
private String from;
private String to;
private String cc;
private String bcc;
private String subject;
private String body;
private String fileName;
private String filePath;
//
}
业务实现类
public interface MailService
{
void sendSimpleMail(Mail mail);
}
// 实现类
@Component
public class MailServiceImpl implements MailService
{
private Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
@Autowired
private JavaMailSenderImpl mailSender;
@Autowired
private SpringTemplateEngine templateEngine;
public void sendSimpleMail(Mail mail)
{
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(mail.getFrom());
message.setTo(mail.getTo());
message.setSubject(mail.getSubject());
message.setText(mail.getBody());
mailSender.send(message);
logger.info("发送完毕");
}
}
测试类
@RestController
@RequestMapping("mail")
public class MailController
{
@Autowired
private MailService mailService;
@Async
@GetMapping("sendSimplEmail")
public String sendSimplEmail()
{
Mail mail = new Mail();
mail.setFrom("xx@qq.com);
mail.setTo("yyy@qq.com");
mail.setSubject("测试邮件");
mail.setBody("这是一封测试邮件");
mailService.sendSimpleMail(mail);
return "发送成功";
}
注意:邮件功能需要异步发送,所以采用的@Async注解来实现。
至此简单的邮件发送功能已经完成。
扩展功能
发送Html内容的邮件
发送简单的邮件,有时候无法满足业务的需求,我们需要至此发送带HTMl内容格式的邮件。
业务实现类
public void sendHtmlMail(Mail mail)
{
MimeMessage message =mailSender.createMimeMessage();
MimeMessageHelper messageHelper=null;
try
{
// 设置编码utf-8
messageHelper = new MimeMessageHelper(message, true, "UTF-8");
messageHelper.setFrom(mail.getFrom());
messageHelper.setTo(mail.getTo());
messageHelper.setSubject(mail.getSubject());
//转换html
messageHelper.setText(mail.getBody(),true);
mailSender.send(message);
}
catch (MessagingException e)
{
logger.error("发送邮件失败");
throw new RuntimeException("发送邮件失败",e);
}
logger.info("发送完毕");
}
注意事项: 1.采用html格式的邮件需要注意内容的格式,采用UTF-8格式否则中文会出现乱码。 2.设置邮件内容时,需要将设置为true,否则html内容会原本输出。
测试类
@Async
@GetMapping("sendHtmlEmail")
public String sendHtmlEmail()
{
Mail mail = new Mail();
mail.setFrom("xx@qq.com);
mail.setTo("yyy@qq.com");
mail.setSubject("测试html格式邮件");
String content = "<html>\n" +
"<body>\n" +
"<h3>hello! 这是测试html内容邮件!</h3>\n" +
"</body>\n" +
"</html>";
mail.setBody(content);
mailService.sendHtmlMail(mail);
return "发送成功";
}
发送带附件邮件
业务实现类
public void sendAttachmentsMail(Mail mail)
{
MimeMessage message =mailSender.createMimeMessage();
MimeMessageHelper messageHelper=null;
try
{
// 设置编码utf-8
messageHelper = new MimeMessageHelper(message, true, "UTF-8");
messageHelper.setFrom(mail.getFrom());
messageHelper.setTo(mail.getTo());
messageHelper.setSubject(mail.getSubject());
//转换html
messageHelper.setText(mail.getBody(),true);
// 附件
FileSystemResource resourse = new FileSystemResource(new File(mail.getFilePath()));
// 附件名称和路径
messageHelper.addAttachment(mail.getFileName(), resourse);
mailSender.send(message);
}
catch (MessagingException e)
{
logger.error("发送邮件失败");
throw new RuntimeException("发送邮件失败",e);
}
logger.info("发送完毕");
}
测试类
@Async
@GetMapping("sendAttachmentsMail")
public String sendAttachmentsMail()
{
Mail mail = new Mail();
mail.setFrom("xx@qq.com);
mail.setTo("yyy@qq.com");
mail.setSubject("测试附件邮件");
mail.setBody("测试附件邮件,有附件请下载");
mail.setFilePath("E:\\cfg\\test.png");
mail.setFileName("test.png");
mailService.sendAttachmentsMail(mail);
return "发送成功";
}
注意:设置附件的路径和附件的名称。
发送模板邮件
有些特殊需要,我们需要采用固定的邮件模板发送邮件。
邮件的模板可以采用thymeleaf和freemark来实现,本文将采用thymeleaf来实现邮件模板发送。
添加依赖
<!-- thymeleaf 模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.2.14</version>
</dependency>
模板内容
模板路径:src/main/resources/templates/emailTemplate.html
模板内容:
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>mail</title>
</head>
<body>
<table align="center" cellpadding="0" cellspacing="0" width="600px" style="margin-bottom:20px">
<tr>
<td>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="600"
style="border-collapse: collapse;">
<tr>
<td bgcolor="#ffffff">
<h3>邮件模板</h3>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="2" style="padding: 0 0 3px 0">
公司名称:<span th:text="${emailParam.companyName}"></span>
</td>
</tr>
<tr>
<td style="padding: 12px 0 3px 0">
地址:<span th:text="${emailParam.address}"></span>
</td>
</tr>
<tr>
<td style="padding: 12px 0 3px">
联系人:<span th:text="${emailParam.phone}"></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
业务实现类
public void sendTemplateMail(Mail mail)
{
Context context = new Context();
Map<String, Object> emailParam = new HashMap<>();
emailParam.put("companyName", "公司名称");
emailParam.put("address", "公司地址");
emailParam.put("phone", "联系电话");
context.setVariable("emailParam", emailParam);
//模板合成html内容
String emailTemplate = templateEngine.process("emailTemplate", context);
mail.setBody(emailTemplate);
sendHtmlMail(mail);
}
测试示例
@Async
@GetMapping("sendTemplateEmail")
public String sendTemplateEmail()
{
Mail mail = new Mail();
mail.setFrom("xx@qq.com);
mail.setTo("yyy@qq.com");
mail.setSubject("测试模板邮件");
mailService.sendTemplateMail(mail);
return "发送成功";
}
总结
本文讲解的是Spring Boot集成JavaMailSender发送邮件,邮件内容格式有种,需要结合业务的来选择对应的实现方式。
到此这篇关于Spring Boot集成JavaMailSender发送邮件功能的文章就介绍到这了,更多相关SpringBoot JavaMailSender发邮件内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!