暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

SpringBoot详细教程 | 第十一篇:Spring Boot中使用JavaMailSender发送邮件

小东IT技术分享 2019-02-24
480

相信使用过Spring的众多开发者都知道Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用JavaMailSender发送邮件。

1.引入依赖

在Spring Boot的工程中的pom.xml中引入spring-boot-starter-mail依赖:

  1. <dependency>

  2.    <groupId>org.springframework.boot</groupId>

  3.    <artifactId>spring-boot-starter-mail</artifactId>

  4. </dependency>

如其他自动化配置模块一样,在完成了依赖引入之后,只需要在application.properties中配置相应的属性内容。

下面我们以QQ邮箱为例,在application.properties中加入如下配置(注意替换自己的用户名和密码):


  1. #QQ邮箱

  2. spring.mail.host=smtp.qq.com

  3. #发送者邮箱需要和实际发送者一致,否则报错501

  4. spring.mail.username=757479746@qq.com

  5. #发送者邮箱的授权码,不是密码,自己去qq邮箱设置

  6. spring.mail.password=

  7. # 设置是否需要认证,如果为true,那么用户名和密码就必须的,

  8. # 如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的

  9. spring.mail.properties.mail.smtp.auth=true

  10. spring.mail.properties.mail.smtp.starttls.enable=true

  11. spring.mail.properties.mail.smtp.starttls.required=true


2.通过单元测试来实现一封简单邮件的发送:

  1. package com.li.springbootmail.test;


  2. import org.junit.Test;

  3. import org.junit.runner.RunWith;

  4. import org.springframework.beans.factory.annotation.Autowired;

  5. import org.springframework.beans.factory.annotation.Value;

  6. import org.springframework.boot.test.context.SpringBootTest;

  7. import org.springframework.mail.SimpleMailMessage;

  8. import org.springframework.mail.javamail.JavaMailSender;

  9. import org.springframework.test.context.junit4.SpringRunner;


  10. /**

  11. * @ClassName MailTest

  12. * @Author lihaodong

  13. * @Date 2019/2/24 18:53

  14. * @Mail lihaodongmail@163.com

  15. * @Description

  16. * @Version 1.0

  17. **/


  18. @RunWith(SpringRunner.class)

  19. @SpringBootTest

  20. public class MailTest {


  21.    /**

  22.     * 获取JavaMailSender bean

  23.     */

  24.    @Autowired

  25.    private JavaMailSender javaMailSender;


  26.    /**

  27.     * 获取配置文件的username

  28.     */

  29.    @Value("${spring.mail.username}")

  30.    private String username;


  31.    /**

  32.     * 实现发送简单的邮件

  33.     */

  34.    @Test

  35.    public void sendSimpleMail1() {

  36.        SimpleMailMessage message = new SimpleMailMessage();

  37.        //设定邮件参数

  38.        //发送者

  39.        message.setFrom(username);

  40.        //接收者

  41.        message.setTo("lihaodongmail@163.com");

  42.        //主题

  43.        message.setSubject("测试主题");

  44.        //邮件内容

  45.        message.setText("测试内容");

  46.        // 发送邮件

  47.        javaMailSender.send(message);

  48.    }

  49. }

到这里,一个简单的邮件发送就完成了,运行一下该单元测试,看看效果如何 启动测试程序,查看邮箱

PS:

由于Spring Boot的starter模块提供了自动化配置,所以在引入了spring-boot-starter-mail依赖之后,会根据配置文件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使用的地方直接@Autowired来引入邮件发送对象。

3.发送附件邮箱

在上面单元测试中加入如下测试用例(通过MimeMessageHelper来发送一封带有附件的邮件):

  1.    /**

  2.     * 发送附件邮箱

  3.     * @throws Exception

  4.     */

  5.    @Test

  6.    public void sendAttachmentsMail() throws Exception {


  7.        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

  8.        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

  9.        helper.setFrom(username);

  10.        helper.setTo("lihaodongmail@163.com");

  11.        helper.setSubject("测试主题:有附件");

  12.        helper.setText("测试内容:有附件的邮件");

  13.        FileSystemResource file = new FileSystemResource(new File("weixin_qrcode.jpg"));

  14.        helper.addAttachment("附件-1.jpg", file);

  15.        helper.addAttachment("附件-2.jpg", file);

  16.        javaMailSender.send(mimeMessage);


  17.    }

启动测试程序,查看邮箱

4.嵌入静态资源

  1.    /**

  2.     * 发送静态邮箱

  3.     * @throws Exception

  4.     */

  5.    @Test

  6.    public void sendStaticMail() throws Exception {

  7.        MimeMessage mimeMessage = javaMailSender.createMimeMessage();


  8.        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

  9.        helper.setFrom(username);

  10.        helper.setTo("lihaodongmail@163.com");

  11.        helper.setSubject("测试主题:嵌入静态资源");

  12.        helper.setText("<html><body><img src=\"cid:weixin_qrcode\" ></body></html>", true);

  13.        FileSystemResource file = new FileSystemResource(new File("weixin_qrcode.jpg"));

  14.        // addInline函数中资源名称jpg需要与正文中cid:weixin_qrcode对应起来

  15.        helper.addInline("weixin_qrcode", file);

  16.        javaMailSender.send(mimeMessage);


  17.    }

启动测试程序,查看结果

5.发送模板邮件

以Freemarker为例

引入依赖

  1.        <dependency>

  2.            <groupId>org.springframework.boot</groupId>

  3.            <artifactId>spring-boot-starter-freemarker</artifactId>

  4.        </dependency>


在resources/templates/下,创建一个模板页面mail.ftl:

  1. <html>

  2. <body>

  3. <h3>你好, <span style="color: red;">${userName}</span>, 这是一封模板邮件!</h3>

  4. </body>

  5. </html>

我们之前在Spring Boot中开发Web应用时,提到过在Spring Boot的自动化配置下,模板默认位于resources/templates/目录下

最后,我们在单元测试中加入发送模板邮件的测试用例,具体如下:

  1. /**

  2.     * 发送模板信息

  3.     * @throws Exception

  4.     */

  5.    @Test

  6.    public void sendTemplateMail() throws Exception {


  7.        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

  8.        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

  9.        helper.setFrom(username);

  10.        helper.setTo("lihaodongmail@163.com");

  11.        helper.setSubject("测试主题:模板邮件");

  12.        /**

  13.         * 模板内需要的参数,保持一致

  14.         */

  15.        Map<String, Object> params = new HashMap<>();

  16.        params.put("userName", "lihaodong");

  17.        /**

  18.         * 配置FreeMarker模板路径

  19.         */

  20.        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);

  21.        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

  22.        String html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);

  23.        helper.setText(html, true);


  24.        javaMailSender.send(mimeMessage);

  25.    }

启动测试程序,查看邮箱

OK,这就是发送邮箱的所有类型

源码下载:https://github.com/LiHaodong888/SpringBootLearn



文章转载自小东IT技术分享,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论