转载

springboot之注册发送邮件

具体使用

以前使用JavaMail实现邮件发送,但是使用比较繁琐,容易出错,为此spring为我们封装了下,通过使用javamailsender简化了我们的操作,springboot则是 Spring 的一套快速配置脚手架,对spring进行了封装,这里我就使用springboot集成邮件注册。

  1. pom依赖添加

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    复制代码
  2. 邮件工具类

    package com.lytw13.demo.util;

    import javax.mail.internet.MimeMessage;


    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.stereotype.Component;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;
    import org.thymeleaf.context.EngineContext;
    import org.thymeleaf.context.IContext;

    import java.io.File;
    import java.util.List;

    @Component
    public class MailUtil {
    private static String from;
    private static String subject;
    private static String text;
    private static JavaMailSender sender;
    private static TemplateEngine templateEngine;

    @Value(value = " ¨ E 123 E s p r i n g . m a i l . u s e r n a m e ¨ E 125 E " ) p r i v a t e v o i d s e t F r o m ( S t r i n g f r o m ) ¨ E 123 E M a i l U t i l . f r o m ¨ E 61 E f r o m E 125 E @ V a l u e ( v a l u e ¨ E 61 E "{spring.mail.username}")
    private void setFrom(String from) {
    MailUtil.from = from;
    }
    @Value(value = "¨E123Espring.mail.username¨E125E")privatevoidsetFrom(Stringfrom)¨E123EMailUtil.from¨E61Efrom;¨E125E@Value(value¨E61E"{spring.mail.subject}")
    private void setSubject(String subject) {
    MailUtil.subject = subject;
    }
    @Value(value = "${spring.mail.text}")
    private void setText(String text) {
    MailUtil.text = text;
    }
    @Autowired
    private void setJavaMailSender(JavaMailSender javaMailSender){
    MailUtil.sender = javaMailSender;
    }
    @Autowired
    private void setTemplateEngine(TemplateEngine templateEngine) {
    MailUtil.templateEngine = templateEngine;
    }
    private static Logger logger = LoggerFactory.getLogger(MailUtil.class);

    public static void sendSimpleMail(String to) {
    try {
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setFrom(from);
    simpleMailMessage.setTo(to);
    simpleMailMessage.setSubject(subject);
    simpleMailMessage.setText(text);
    sender.send(simpleMailMessage);
    logger.info("发送邮件成功!");
    }catch(Exception e) {
    logger.error("发送邮件出现错误!",e);
    }
    }
    public static void sendHtmlMail(String to,String content, List<String> attachFileList) {
    try {
    MimeMessage mimeMessage = sender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
    mimeMessageHelper.setFrom(from);
    mimeMessageHelper.setTo(to);
    mimeMessageHelper.setSubject(subject);
    mimeMessageHelper.setText(content,true);
    if(attachFileList != null && attachFileList.size() > 0) {
    for (String filePath:attachFileList
    ) {
    File file = new File(filePath);
    String fileName = filePath.substring(filePath.lastIndexOf("//")+1);
    mimeMessageHelper.addAttachment(fileName,file);
    }
    }
    sender.send(mimeMessage);
    logger.info("发送邮件成功!");
    } catch (Exception e) {
    logger.error("发送邮件出现错误!",e);
    }
    }

    public static void sendHtmlTemplateMail(String to, String name, List<String> attachFileList) {
    try {
    MimeMessage mimeMessage = sender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
    mimeMessageHelper.setFrom(from);
    mimeMessageHelper.setTo(to);
    mimeMessageHelper.setSubject(subject);
    //存放变量
    Context context = new Context();
    context.setVariable("name", name);
    String template = templateEngine.process("mailTemplate", context);
    mimeMessageHelper.setText(template,true);
    if(attachFileList != null && attachFileList.size() > 0) {
    for (String filePath:attachFileList
    ) {
    File file = new File(filePath);
    String fileName = filePath.substring(filePath.lastIndexOf("//")+1);
    mimeMessageHelper.addAttachment(fileName,file);
    }
    }
    sender.send(mimeMessage);
    logger.info("发送邮件成功!");
    } catch (Exception e) {
    logger.error("发送邮件出现错误!",e);
    }
    }
    }
    复制代码

    上面我写了3个方法,sendSimpleMail只能发送简单邮件,不能添加附件,sendHtmlMail方法能添加附件,并支持发送HTML邮件内容,最后一个方法则是支持使用HTML模板发送邮件,支持附件。日常生活中,我们可能有时候会收到类似这样的邮件:

    尊敬的用户xxxxx,您好!欢迎您加入lytw13网站!
      您的lytw13账号已经成功创建,请点击这里激活账号。
    复制代码

    可以看到我们上面的只有注册者名字会变化,这时候我们直接定义一个模板,然后为里面设置用户名即可。前两种方法比较简单,而且实际中相对较少,所以下面我就以模板方式发送邮件。

  3. application.yml配置文件

    server:
     port: 8080
    spring:
     mail:
       host: smtp.163.com  //邮件服务器地址
       username: lytw1315@163.com 
       password: lllllll  
       subject: "欢迎注册!"
       text: "欢迎注册lytw13's blog!"
     datasource:
       username: root
       password: 123456
       driver-class-name: com.mysql.cj.jdbc.Driver
       url: jdbc:mysql://localhost:3306/db_demo_sys?serverTimezone=Asia/Shanghai
    mybatis:
     mapper-locations: classpath:mapper/*.xml
     config-location: classpath:mybatis/mybatis.xml
    复制代码
  4. controller

    @RestController
    @RequestMapping("user")
    public class UserController {
       @Autowired
       UserService userService;
    
       @PostMapping("save")
       public String save(@RequestBody TbUser user) {
           userService.save(user);
           return "success";
       }
    }
    复制代码
  5. service

    package com.lytw13.demo.service.impl;
    
    import com.lytw13.demo.dao.UserMapper;
    import com.lytw13.demo.model.TbUser;
    import com.lytw13.demo.service.UserService;
    import com.lytw13.demo.util.MailUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Service
    public class UserServiceImpl implements UserService {
       @Autowired
       UserMapper userMapper;
       @Override
       public void save(TbUser user) {
           long startTime = System.currentTimeMillis();
           userMapper.insert(user);
           List<String> fileList = new ArrayList<>();
           fileList.add("E://others//MyBlog//新建文本文档1.txt");
           fileList.add("E://others//MyBlog//新建文本文档.txt");
           MailUtil.sendHtmlTemplateMail(user.getEmail(),user.getName(),fileList);
           long endTime = System.currentTimeMillis();
           System.out.println("耗时:"+(endTime-startTime));
       }
    }
    复制代码

    dao和mapper就不粘贴了。

  6. 邮件模板

    这里我使用的是thymeleaf,上面封装解析模板的也是用的thymeleaf专有的方法,使用freemarker还得自己修改下上面的方法。

I. pom依赖

     <dependency>
        <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
复制代码

II. HTML邮件模板

 <!DOCTYPE html>
 <html xmlns:th="http://www.thymeleaf.org">
 <head>
 <meta charset="UTF-8">
 <title>Insert title here</title>
 </head>
 <body>
     <div>
         尊敬的用户<span th:text="${name}"></span>,您好!欢迎您加入lytw13网站!
     <br>
         您的lytw13账号已经成功创建,请点击<a th:href="@{localhost:8080/user/activeUser(name=${name},ustatus=1)}">这里</a>激活账号。

     </div>
 </body>
 </html>
复制代码

测试

因为是post请求,浏览器不能直接用,所以用的POSTMAN测试的。

springboot之注册发送邮件
email_ceshi1

上面我记录了下耗时,以后我还会集成rabbitmq,可以 对比下,这个同步串行耗时很严重的,这里还只是发送邮件,没有别的操作还。

springboot之注册发送邮件
email_ceshi1jieguo

具体代码我已经上传到了github,如果有问题可以参考下。 前往

原文  https://juejin.im/post/5e00d829e51d45584006eb1a
正文到此结束
Loading...