首页 > 技术文章 > springboot mail邮件发送+随机字符串验证码

BoofieWoo 2020-08-26 11:11 原文

springboot mail 邮件发送

开通邮箱服务(此处以新浪邮箱为例)

导入pom 依赖

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

配置yml

spring:
mail:
  host: smtp.sina.com #发送邮件服务器
  port: 465
  username: xxxxxxxxx@sina.com #发送邮件的邮箱地址
  password: xxxxxxxxxxxxx #客户端授权码,不是邮箱密码,网易的是自己设置的
  protocol: smtps
  properties.mail.smtp.ssl.enable: true
  default-encoding: utf-8

编写邮件util方法

此处建议开启线程,邮箱验证一般较慢,容易阻塞

@Service
public class MailClient{
   /**
    * Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
    */
   @Resource
   private JavaMailSender mailSender;

   /**
    * 配置文件中我的邮箱
    */
   @Value("${spring.mail.username}")
   private String from;

   /**
    * 简单文本邮件
    * @param to 收件人
    * @param subject 主题
    * @param content 内容
    */
   public void sendSimpleMail(String to, String subject, String content) {
       new Thread(()->{
           //创建SimpleMailMessage对象
           SimpleMailMessage message = new SimpleMailMessage();
           //邮件发送人
           message.setFrom(from);
           //邮件接收人
           message.setTo(to);
           //邮件主题
           message.setSubject(subject);
           //邮件内容
           message.setText(content);
           //发送邮件
           mailSender.send(message);
      }).start();
  }
}

编写controller生成随机验证码

随机代码utils

public class AuthUtil {
   //length用户要求产生字符串的长度
   public static String getRandomString(int length){
       String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
       Random random=new Random();
       StringBuffer sb=new StringBuffer();
       for(int i=0;i<length;i++){
           int number=random.nextInt(62); //62 是字符串模板str的长度str[0...61]
           sb.append(str.charAt(number));
      }
       return sb.toString();
  }
}

发送邮件controller

@Controller
public class MailController {
   @Resource
   private EmailUtils emailUtils;

   @ResponseBody
   @RequestMapping("/")
   public String sendMail(){
       emailUtils.sendSimpleMail("boofie@163.com","发送邮件","Hello Boofie!您的验证码是:"+AuthUtil.getRandomString(4));
       return "OK!";
  }
   @ResponseBody
   @RequestMapping("/a")
   public String sendHtmlMail(){
       emailUtils.sendHtmlMail("boofie@163.com","发送邮件",
                               "<a href='http://www.bilibili.com'>Hello Boofie!</a><br>验证码:"+ AuthUtil.getRandomString(6));
       return "OK!";
  }
}



推荐阅读