SpringBoot项目发送邮件进行注册时验证

因为各大邮件都有其对应安全系统,不是项目中想用就可以用的,我们必须要拿到其对应的客户端授权码才行,拿到授权码,在项目中置SMTP服务协议以及主机 配置账户 ,就可以在项目中使用各大邮件运营商进行发送邮件了

https://blog.csdn.net/leilei1366615/article/details/104868250/

获取QQ邮箱授权码

登陆qq邮箱后,点击设置 -> 选择 -> 账户选项

向下拉选择开启POP3/SMTP 服务

点击开启也会进入验证 验证成功后即可看到自己qq邮箱的客户端授权码了

我们在拿到授权码后,就可以在我们Springboot工程中的配置文件 aplication.yml 或者properties文件中配置了

配置项目

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
spring:
  mail:
    #smtp服务主机  qq邮箱则为smtp.qq.com
    host: smtp.163.com
    #服务协议
    protocol: smtp
    # 编码集
    default-encoding: UTF-8
    #发送邮件的账户
    username: xxxxxxx@163.com
    #授权码
    password: xxxxxx
    test-connection: true
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

其实也非常简单 ,Springboot已经给我们邮件发送进行了非常好的整合了,我们只需要注入邮件发送接口 调用其中的方法,就能轻松而愉悦的进行邮件发送了!

我们只需要在任意交由Spring管理的类(例如你的service层等)下注入以下接口即可

  @Autowired
  private JavaMailSender mailSender;

由于每一封邮件都有固定的内容 例如 收件人信息 邮件内容 邮件标题 那么我们充分利用java面向对象的特性,我们把邮件发送抽取为一个对象

肯定有人纳闷了,那么接收方有了,发送方呢?

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ToEmail implements Serializable {

  /**
   * 邮件接收方,可多人
   */
  private String[] tos;
  /**
   * 邮件主题
   */
  private String subject;
  /**
   * 邮件内容
   */
  private String content;
}

发送一方,肯定就是我们自身拿到的授权码账号啊 ,我们获取账户客户端授权码其目的就是为了让代码代替我们自身邮箱 向其他邮箱发送信息而已。

获取发送方账户信息

  @Value("${spring.mail.username}")
  private String from;

统一说明: R为我项目自定义的Ajax 响应,结合 RestController 或者Responsebody向前端返回统一的JSON格式数据

简单与邮件发送

    @ApiOperation("发送邮箱验证码")
    @GetMapping("/sendEmail/{email}")
    public R register(@PathVariable("email") String email){
        String code = RandomUtil.randomNumbers(5);
        //存储120秒
        redisUtils.set(email,code,120);
        String content = "欢迎注册杭州市IT人才需求地图信息系统,注册验证码为:" + code;
        EmailVo emailVo = new EmailVo(new String[]{email},"用户注册验证码", content);
        return commonEmail(emailVo);
    }

    public R commonEmail(EmailVo toEmail) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(toEmail.getTos());
        //邮件标题
        message.setSubject(toEmail.getSubject());
        //邮件内容
        message.setText(toEmail.getContent());
        try {
            mailSender.send(message);
            return R.success().data("发送邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return R.fail().data("邮件发送失败");
        }
    }

或许有人觉得 这样发送邮件 ,内容死板不好看啊,我想搞个有特色的的,搞个有样式的邮件,那么,下边就轮到HTML邮件出场了。

HTML邮件发送

  public R htmlEmail(ToEmail toEmail) throws MessagingException {
    //创建一个MINE消息
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
    //谁发
    minehelper.setFrom(from);
    //谁要接收
    minehelper.setTo(toEmail.getTos());
    //邮件主题
    minehelper.setSubject(toEmail.getSubject());
    //邮件内容   true 表示带有附件或html
    minehelper.setText(toEmail.getContent(), true);
    try {
      mailSender.send(message);
      return R.ok(toEmail.getTos() + toEmail.getContent(), "HTML邮件成功");
    } catch (MailException e) {
      e.printStackTrace();
      return R.error("HTML邮件失败");
    }
  }

由于html格式不好编写,我直接使用Springboot测试类了

    @Test
    public void testHtml() throws Exception {
        String content = "<html>\n" +
            "<body>\n" +
            "    <h1>这是Html格式邮件!,不信你看邮件,我字体比一般字体还要大</h1>\n" +
            "</body>\n" +
            "</html>";
        toEmailService.htmlEmail(new ToEmail(new String[]{"248721866@qq.com"},"Html邮件",content));
    }

有的人还喜欢在邮件中添加一些图片,让图片作为邮件内容 ,,这也是可以的

含静态资源邮件发送

我这里只是列举了发送一张图片,如需发送多张,修改修改其中一点方法即可,代码注释的非常详细了

public R staticEmail(ToEmail toEmail, MultipartFile multipartFile, String resId) {
    //创建一个MINE消息
    MimeMessage message = mailSender.createMimeMessage();
    try {
      MimeMessageHelper helper = new MimeMessageHelper(message, true);
      //谁发
      helper.setFrom(from);
      //谁接收
      helper.setTo(toEmail.getTos());
      //邮件主题
      helper.setSubject(toEmail.getSubject());
      //邮件内容   true 表示带有附件或html
      //邮件内容拼接
      String content =
          "<html><body><img width='250px' src=\'cid:" + resId + "\'>" + toEmail.getContent()
              + "</body></html>";
      helper.setText(content, true);
      //蒋 multpartfile 转为file
      File multipartFileToFile = MultipartFileToFile(multipartFile);
      FileSystemResource res = new FileSystemResource(multipartFileToFile);

      //添加内联资源,一个id对应一个资源,最终通过id来找到该资源
      helper.addInline(resId, res);
      mailSender.send(message);
      return R.ok(toEmail.getTos() + toEmail.getContent(), "嵌入静态资源的邮件已经发送");
    } catch (MessagingException e) {
      return R.error("嵌入静态资源的邮件发送失败");
    }
  }

因为我当前没有使用文件服务器嘛,并未使用文件上传的URL 而是直接向接口传的multipartFile文件对象,但是邮件需要的是File对象,所以我们这里需要将multipartFile 转为 File

private File MultipartFileToFile(MultipartFile multiFile) {
    // 获取文件名
    String fileName = multiFile.getOriginalFilename();
    // 获取文件后缀
    String prefix = fileName.substring(fileName.lastIndexOf("."));
    // 若需要防止生成的临时文件重复,可以在文件名后添加随机码

    try {
      File file = File.createTempFile(fileName, prefix);
      multiFile.transferTo(file);
      return file;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

发附件需要注意的是一个静态资源要对应一个ID ,ID没有讲究 别重复了就行

带附件邮件发送

很多时候,我们在发送邮件的时候,需要携带一些附件一起发送,那么JavaMailSender 中呢,也是有携带附件的方法的

    public R enclosureEmail(ToEmail toEmail, MultipartFile multipartFile) {
        //创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发
            helper.setFrom(from);
            //谁接收
            helper.setTo(toEmail.getTos());
            //邮件主题
            helper.setSubject(toEmail.getSubject());
            //邮件内容   true 表示带有附件或html
            helper.setText(toEmail.getContent(), true);
            File multipartFileToFile = MultipartFileToFile(multipartFile);
            FileSystemResource file = new FileSystemResource(multipartFileToFile);
            String filename = file.getFilename();
            //添加附件
            helper.addAttachment(filename, file);
            mailSender.send(message);
            return R.ok(toEmail.getTos() + toEmail.getContent(), "附件邮件成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            return R.error("附件邮件发送失败" + e.getMessage());
        }
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值