您的位置:首页 > 编程语言 > Java开发

SpringBoot发送邮件

2018-11-18 18:25 288 查看
版权声明:作者已开启版权声明,如转载请注明转载地址。 https://blog.csdn.net/qq_34829447/article/details/84202939

一.背景

1.邮件使用场景

  • 注册验证
  • 网站营销
  • 安全的最后一道防线
  • 提醒、监控告警
  • 触发机制

2.邮件发送原理

  • 邮件传输协议:SMTP协议(Simple Mail Transfer Potical简单邮件传输,从源地址到目标地址的规范,邮件可以接力传送)和POP3协议(Post Office Potical Three)
  • 内容不断发展:IMAP协议(Internet Mail Access Potical交互式存储协议,从浏览器登录邮箱或是客户软件登录邮箱看到的邮件状态都是一致的,是POP3协议的补充)和Mime协议(早期SMTP在二进制处理上并不是很好,Mime支持传送二进制文件)

3.邮件发送历史

  • 1969年10月,世界上的第一封电子邮件
  • 1987年9月14日中国第一封电子邮件
  • 30年发展历史
  • Java发送邮件
  • Spring发送邮件
  • SpringbootMail发送邮件

4.SpringBoot介绍

  • 约定大于配置
  • 简单快速开发
  • 强大的生态链
  • SpringBoot和发送邮件

5.前置知识

  • 会使用Spring进行开发
  • 对Spring Boot有一定的了解
  • Maven\HTML\Thymeleaf等

二.实践

1.发送文本邮件

  • 发送简单文本邮件步骤

    引入相关Jar包
  • 配置邮件参数
  • 封装SimpleMailMessage
  • 使用JavaMailSender进行发送
  • 使用Junit Test进行测试
  • 配置文件

      在pom.xml中添加插件

      <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-mail</artifactId>
      </dependency>
    • 在application.properties文件中添加配置

      spring.mail.host=smtp.qq.com
      spring.mail.username=674112795@qq.com
      spring.mail.password=password
      spring.mail.default-encoding=utf-8
  • 在service中添加发送邮件的方法

    //service.java
    //param1 发送给谁
    //param2 发送主题
    //param3 发送内容
    public class MailService{
    @Value("${spring.mail.username}")
    private String from;//从配置文件中注入
    
    @Autowired
    private JavaMailSender mailSender;
    
    public void sendSimpleMail(String to,String subject,String content){
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    message.setFrom(from);
    mailSender.send(message);
    }
    }
  • 2.发送HTML邮件

    • 在service中添加新的方法

      //param1 发送给谁
      //param2 发送主题
      //param3 发送内容
      public class MailService{
      @Value("${spring.mail.username}")
      private String from;//从配置文件中注入
      
      @Autowired
      private JavaMailSender mailSender;
      
      public void sendSimpleMail(String to,String subject,String content){
      SimpleMailMessage message = new SimpleMailMessage();
      message.setTo(to);
      message.setSubject(subject);
      message.setText(content);
      message.setFrom(from);
      mailSender.send(message);
      }
      
      public void sendHTMLMail(String to,String subject,String content) throws MessagingException{
      MimeMessage message = mailSender.createMimeMessage();
      MimeMessageHelper helper = new MimeMessageHelper(message,true);
      helper.setFrom(from);
      helper.setTo(to);
      helper.setSubject(subject);
      helper.setText(context,true);
      mailSender.send(message);
      }
      }

    3.发送邮件附件

    • 在service中添加新的方法

      //param1 发送给谁
      //param2 发送主题
      //param3 发送内容
      public class MailService{
      @Value("${spring.mail.username}")
      private String from;//从配置文件中注入
      
      @Autowired
      private JavaMailSender mailSender;
      
      public void sendSimpleMail(String to,String subject,String content){
      SimpleMailMessage message = new SimpleMailMessage();
      message.setTo(to);
      message.setSubject(subject);
      message.setText(content);
      message.setFrom(from);
      mailSender.send(message);
      }
      
      public void sendHTMLMail(String to,String subject,String content) throws MessagingException{
      MimeMessage message = mailSender.createMimeMessage();
      MimeMessageHelper helper = new MimeMessageHelper(message,true);
      helper.setFrom(from);
      helper.setTo(to);
      helper.setSubject(subject);
      helper.setText(content,true);
      mailSender.send(message);
      }
      
      public void sendAttachmentMail(String to,String subject,String content,String filePath) throws MessagingException{//filePath为附件路径
      MimeMessage message = mailSender.createMimeMessage();
      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 = file.getFilename();//获得文件名
      helper.addAttachment(fileName,file);
      helper.addAttachment("_"+fileName,"_"+file);//发送多个附件
      mailSender.send(message);
      }
      }

    4.带图片的邮件

    • 在service中添加新的方法

      //param1 发送给谁
      //param2 发送主题
      //param3 发送内容
      public class MailService{
      @Value("${spring.mail.username}")
      private String from;//从配置文件中注入
      
      @Autowired
      private JavaMailSender mailSender;
      
      public void sendSimpleMail(String to,String subject,String content){
      SimpleMailMessage message = new SimpleMailMessage();
      message.setTo(to);
      message.setSubject(subject);
      message.setText(content);
      message.setFrom(from);
      mailSender.send(message);
      }
      
      public void sendHTMLMail(String to,String subject,String content) throws MessagingException{
      MimeMessage message = mailSender.createMimeMessage();
      MimeMessageHelper helper = new MimeMessageHelper(message,true);
      helper.setFrom(from);
      helper.setTo(to);
      helper.setSubject(subject);
      helper.setText(content,true);//参数二表示是否是html格式
      mailSender.send(message);
      }
      
      public void sendAttachmentMail(String to,String subject,String content,String filePath) throws MessagingException{//filePath为附件路径
      MimeMessage message = mailSender.createMimeMessage();
      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 = file.getFilename();//获得文件名
      helper.addAttachment(fileName,file);
      helper.addAttachment("_"+fileName,"_"+file);//发送多个附件
      mailSender.send(message);
      }
      
      //表示在正文中添加图片
      public void sendInlinResourceMail(String to,String subject,String content,String rscPath,String rscId) throws MessagingException {//rscPath表示图片地址
      MimeMessage message = mailSender.createMimeMessage();
      MimeMessageHelper helper = new MimeMessageHelper(message,true);
      helper.setFrom(from);
      helper.setTo(to);
      helper.setSubject(subject);
      helper.setText(content,true);
      //用于读取文件
      FileSystemResource res = new FileSystemResource(new File(rscPath));
      helper.addInline(rscId,res);
      //发送多个图片则多写几个上述两行代码即可
      mailSender.send(message);
      }
      //在测试时的部分内容
      //String imgPath = "/jack/destop/1.jpg";//文件路径
      //String rscId = "jack001";//图片ID
      //String content = "<html><body>这是有图片的邮件<img src=\'cid:"+rscId+"\'></img></body></html>"//将id放进去,到邮件获取时将自动带入图片
      }

    5.邮件模板

    • 邮件的主体内容不变化的邮件,我们通常使用模板邮件

    • 常用的模板邮件:FreeMarker,Velocity,thymeleaf

    • 引入thymeleaf依赖包

      <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
    • 创建邮件模板,在templetes文件夹下创建emailThymeleaf.html

      <!DOCTYPE html>
      <!-- 使用xmlns声明为thymeleaf模板 -->
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
      <meta charset="UTF-8">
      <title>邮件模板</title>
      </head>
      <body>
      您好,感谢您的注册,这是一封验证邮件,请点击下面的连接完成注册,感谢您的支持!<br/>
      <a href="#" th:href="@{http://www.baidu.com/s(wd=${keyword})}">激活账户</a>
      </body>
      </html>
    • 添加测试模板内容

      @RunWith(SpringRunner.class)
      @SpringBootTest
      public class ServiceTest{
      @Resource
      TemplateEngine templateEngine;//添加thyleaf模板引擎,用于解析模板
      @Test
      public void testTemplateMailTest() throws MessagingException {
      Context context = new Context();
      context.setVariable("keyword","springboot");
      String emailContent = templateEngine.process("emailThymeleaf",context);//参数一模板引擎名字,第二个参数是变量键值,读出一个html的文本
      emailService.sendHTMLMail("mrjackzhe@gmail.com","这是一个模板邮件",emailContent);
      }
      }
    • 模板邮件的思路其实发送的也是html,只不过构建的时候有对应的html模板,只需要在模板中添加对应的内容即可

    • 完整的测试内容

      package com.example.demo.service;
      
      import org.junit.Test;
      import org.junit.runner.RunWith;
      import org.springframework.boot.test.context.SpringBootTest;
      import org.springframework.context.ApplicationContext;
      import org.springframework.test.context.junit4.SpringRunner;
      import org.thymeleaf.TemplateEngine;
      import org.thymeleaf.context.Context;
      
      import javax.annotation.Resource;
      import javax.mail.MessagingException;
      
      @RunWith(SpringRunner.class)
      @SpringBootTest
      public class EmailServiceTest {
      @Resource
      public EmailService emailService;
      
      @Resource
      TemplateEngine templateEngine;//添加thyleaf模板引擎,用于解析模板
      
      @Test
      public void testEmail(){
      emailService.sendSimpleMail("xxx@163.com","test","这只是个测试");
      }
      
      @Test
      public void testHTMLEmail() throws MessagingException {
      String str = "<h1>hello</h1>";
      emailService.sendHTMLMail("xxx@163.com","test",str);
      }
      
      @Test
      public void testAttachmentMail() throws MessagingException {
      String str = "<h1>This is attachment mail</h1>";
      String imgPath = "/Users/wangzhe/Desktop/QQ20181002-115714@2x.jpg";
      emailService.sendAttachmentMail("xxx@163.com","testAttachment",str,imgPath);
      }
      
      @Test
      public void testImageMail() throws MessagingException {
      String imgPath = "/Users/wangzhe/Desktop/QQ20181002-115714@2x.jpg";//文件路径
      String rscId = "001";//图片ID
      String content = "<html><body>这是有图片的邮件<img src=\'cid:"+rscId+"\'></img></body></html>";//将id放进去,到邮件获取时将自动带入图片
      emailService.sendInlinResourceMail("xxx@163.com","testImage",content,imgPath,rscId);
      }
      
      @Test
      public void testTemplateMailTest() throws MessagingException {
      Context context = new Context();
      context.setVariable("keyword","springboot");
      String emailContent = templateEngine.process("emailThymeleaf",context);//参数一模板引擎名字,第二个参数是变量键值,读出一个html的文本
      emailService.sendHTMLMail("xxx@163.com","这是一个模板邮件",emailContent);
      }
      }

    6.邮件系统

    • 通常项目中,我们通常使用异步来发送邮件,所以不能throw出来异常,而通常采用logger的形式记录错误信息
    • 常见错误 421 HL:LCC 该IP通常并发连接数过大
    • 451 Requested mail action not taken:too much fail … 登录失败次数过多,被临时禁止登陆
    • 553 authentication is required 认证失败
    阅读更多
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: