Spring发送电子邮件

简介

Spring基于javax.mail封装了一套用于发送电子邮件的API,位于org.springframework.mail包下,下面将介绍下发送普通文本邮件和基于thymeleaf模版的邮件。

普通邮件

导入javax.mail依赖

<!-- ...... -->
<!-- 省略Spring依赖 -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

Spring配置类

@PropertySource(value="classpath:mail.properties")
@Configuration
public class SpringConfig {
	@Autowired
	Environment environment;
	
	/**
	 * Spring邮件配置
	 */
	@Bean
	public JavaMailSenderImpl javaMailSenderImpl(){
		JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
		javaMailSenderImpl.setHost(environment.getProperty("mail.host"));
		javaMailSenderImpl.setUsername(environment.getProperty("mail.username"));
		javaMailSenderImpl.setPassword(environment.getProperty("mail.password"));
		javaMailSenderImpl.setDefaultEncoding(environment.getProperty("mail.encoding"));
		return javaMailSenderImpl;
	}
}

邮件配置:mail.properties

#QQ邮箱发送邮件服务器
mail.host=smtp.qq.com
#QQ邮箱账户名
mail.username=xxxxxx@qq.com
#QQ邮箱授权码,开启IMAP/SMTP服务时会生成
mail.password=lrorsapyffcwbegg
#邮件发送编码
mail.encoding=UTF-8

测试

@RunWith(SpringRunner.class)
@ContextConfiguration(classes=SpringConfig.class)
public class MailTest {
	@Autowired
	private JavaMailSenderImpl javaMailSenderImpl;
	
	@Test
	public void testSimpleMail() throws MessagingException{
		MimeMessage message = javaMailSenderImpl.createMimeMessage();
		
		//发送带附件和内联元素的邮件需要将第二个参数设置为true
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		
		//发送方邮箱,和配置文件中的mail.username要一致
		helper.setFrom("xxxxxx@qq.com");
		
		//接收方
		helper.setTo("xxxxxx@qq.com");
		
		//主题
		helper.setSubject("邮件测试");
		
		//邮件内容
		helper.setText("<html><body><img src='cid:myphoto'></body></html>", true);
		
		//邮件内容内嵌的图片,addInline中的contentId要和邮件内容中的cid相对应
		FileSystemResource res = new FileSystemResource(new File("e:/yc/1.jpg"));
		helper.addInline("myphoto", res);
		
		//邮件附件
		FileSystemResource file = new FileSystemResource(new File("e:/yc/myphoto.zip"));
		helper.addAttachment("myphoto.zip", file);
		
		javaMailSenderImpl.send(message);
	}
}

基于thymeleaf模版的邮件

导入thymeleaf-spring依赖

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring4</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

Spring配置类中添加thymeleaf模板配置

	@Bean
    public TemplateEngine emailTemplateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setResolvablePatterns(Collections.singleton("*.html"));
        templateResolver.setPrefix("/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(false);
        templateEngine.addTemplateResolver(templateResolver);
        return templateEngine;
    }

模版文件:/src/main/resources/templates/msg.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <style type="text/css">span{color:orange}</style>
  </head>
  <body>
    <p>
      	您好, <span th:text="${name}">xxx</span>,感谢您使用XXX服务,您正在进行邮箱验证,本次请求的验证码为:
    </p>
    <p><span th:text="${validCode}">1111</span>(为了保障您帐号的安全性,请在1小时内完成验证。)</p>
    <p>
      	XXX团队<br />
      	2019年06月06日
    </p>
  </body>
</html>

测试

	@Autowired
	private TemplateEngine emailTemplateEngine;
	
	@Test
	public void testTemplateMail() throws MessagingException{
		MimeMessage message = javaMailSenderImpl.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom("xxxxxx@qq.com");
		helper.setTo("xxxxxx@qq.com");
		helper.setSubject("邮件测试");
		
		//thymeleaf模版解析成String
		Context ctx = new Context();
		ctx.setVariable("name", "小姐姐");
		ctx.setVariable("validCode", "88888888");
		String htmlContent = emailTemplateEngine.process("msg.html", ctx);
		helper.setText(htmlContent, true);
		
		javaMailSenderImpl.send(message);
	}

posted @ 2019-08-01 21:18  布禾  阅读(3581)  评论(0编辑  收藏  举报