Spring发送电子邮件

2019-08-16 11:41:49来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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);
    }


原文链接:https://www.cnblogs.com/seve/p/11281992.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:静态方法

下一篇:Linux下mongoDB下载与安装