Spring Boot 2.x (xviii): Mail service to make a benta

Introduction prospects

In their daily work, we often use the mail service, such as sending a verification code to retrieve password confirmation, registration verification e-mail, so some operations here on mail service.

General idea

In fact, we have to do is to put a Java program as a client and then connect to send email that we use to configure the SMTP protocol (from) corresponding SMTP server, and then through the SMTP protocol, the message to join the target mailbox (to) correspond SMTP server, mail distribution to the final destination mailbox

Spring Boot to our integrated e-mail-related services, and gives the corresponding starter, here we come to learn about the actual mail service is how to play.

The introduction of POM

The first step in the same years: the introduction of the required starter dependence, where I used my Spring Boot corresponding version 2.1.4, version, then the rest should be little difference, as can also learn

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.1.4.RELEASE</version>
</dependency>

Profiles

Because here there are several major domestic carriers mailbox, so divided into four different cases to illustrate

  • QQ-mail

    QQ-mail is a relatively trouble, after need to log into the mailbox to find the corresponding configuration, and verify the password to open STMP service

Click here to get the corresponding authorization code. The next configuration we will use ~

Host personal QQ mailbox SMTP server is: smtp.qq.com

  • 163 E-mail

    Corresponding authorization code that we email password -

    Host SMTP server is: smtp.163.com

  • Tencent E-mail

    Corresponding authorization code is our mailbox password

    Business and personal host is slightly different: smtp.exmail.qq.com

  • Ali E-mail

    Corresponding authorization code is our mailbox password

    Ali E-mail host is: smtp.mxhichina.com

After obtaining the corresponding information, we can improve our configuration information to a ~

# 这里的host对应是上面的几大运营商的STMP服务器的host
spring.mail.host=smtp.163.com
spring.mail.username=****@163.com
# 这里的password对应的就是上面的授权码
spring.mail.password=*** 
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8

Write your message entity class

/**
 * 邮件实体类
 * @author vi
 * @since 2019/07/17
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Mail {

    /**
     * 邮件发送人
     */
    private String from;
  
    /**
     * 邮件接收人
     */
    private String to;
  
    /**
     * 邮件主题
     */
    private String subject;
  
    /**
     * 邮件内容
     */
    private String content;
  
    /**
     * 邮件主题
     */
    private String type;

    /**
     * 发送邮件模板时的模板文件名
     */
    private String templateName;

    /**
     * 模板参数
     */
    private Map<String,Object> variables;

    /**
     * 附件地址
     */
    private String attachPath;

}

The preparation method of sending mail

Here, I will send the message is divided into two situations:

  • Send regular mail
   
     /**
       * 发送普通邮件
       * @param email 邮件对象
       */
      private static void sendSimpleMail(Mail email) {
          SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
  //        邮件发送人
          simpleMailMessage.setFrom(email.getFrom());
  //        邮件接收人
          simpleMailMessage.setTo(email.getTo());
  //        邮件主题
          simpleMailMessage.setSubject(email.getSubject());
  //        邮件内容
          simpleMailMessage.setText(email.getContent());
  //        发送邮件
          javaMailSender.send(simpleMailMessage);
      }
      
     
  • Send e-mail MIME types (such as templates, attachments, HTML belong to this type of mail)

     /**
       * 发送MIME类型的邮件
       * @param email 邮件对象
       */
      private static void sendMimeMail(Mail email) {
  //        生成邮件字符串
          String content = email.getContent();
          if (email.getVariables() != null) {
              content = generate(email);
          }
  //        基于这个对象可以发送HTML,或者携带附件的二进制邮件
          MimeMessage message= javaMailSender.createMimeMessage();
          try {
  //            构建发送模板邮件的对象
              MimeMessageHelper helper = new MimeMessageHelper(message,true);
  //            设置发送邮箱
              helper.setFrom(email.getFrom());
  //            设置接收邮箱
              helper.setTo(email.getTo());
  //            设置邮件名(主题)
              helper.setSubject(email.getSubject());
  //            设置邮件内容
              helper.setText(content,true);
  //            这里可以发送带有附件的邮件,如果没有附件可以省略,就不在多做描述
              if (!StringUtils.isNullOrEmpty(email.getAttachPath())) {
                  FileSystemResource file = new FileSystemResource(new File(email.getAttachPath()));
                  helper.addAttachment(file.getFilename(), file);
              }
  //            发送邮件
              javaMailSender.send(message);
          } catch (MessagingException e) {
  
          }
      }
  
  
     /**
       * 生成模板字符串
       * @param email 邮件对象
       * @return
       */
      private static String generate(Mail email) {
          Context context = new Context();
  //        设置模板参数
          context.setVariables(email.getVariables());
  //        加载模板后的内容字符串
          return templateEngine.process(email.getTemplateName(), context);
      }

最后可以把这两个方法统一接口,通过Mail类中的类型来判断调用哪一个方法即可~

    /**
     * 对外开放的统一发送邮件方法
     * @param mail
     */
    public static void sendEmail(Mail mail) {
        String  type = mail.getType();
        switch (type) {
            case "1":
                sendSimpleMail(mail);
            case "2":
                sendMimeMail(mail);
        }
    }

关于模板的一些补充

如果我们需要发送模板邮件的话,需要使用到模板引擎freemaker或thymeleaf,这里我拿thymeleaf来说一下~

第一步,可以引入pom文件

<dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

第二步,需要在配置文件中进行配置

spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8

第三步,通过我们获取到的模板参数对Mail类进行set方法

mail.setVariables(email.getVariables());

第四步,我们需要在模板中去使用参数

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h3 style="color: red;" th:text="${username}"></h3>
</body>
</html>

注意,这里的thymeleaf的用法,使用标签th:text来赋值,更多的模板用法,可以去

查阅thymeleaf的用法~

后记

邮件在这里就告一段落了,下篇预告:JVM系列(一):JVM简介,敬请期待,谢谢大家一直以来的支持!

公众号

原创文章,文笔有限,才疏学浅,文中若有不正之处,万望告知!

Guess you like

Origin www.cnblogs.com/viyoung/p/11205018.html