基于spring boot实现邮箱发送和邮箱验证
作者:mmseoamin日期:2024-02-24

目录

    • 一、邮箱发送实现
      • 1. 开通邮箱服务
      • 2. 添加邮箱依赖
      • 3.添加配置
      • 4.添加邮箱通用类
      • 5. 测试类
      • 二、邮箱验证实现
        • 1.添加依赖
        • 2. 添加配置
        • 3.添加controller
        • 4. 测试

          项目地址: https://gitee.com/nssnail/springboot-email

          一、邮箱发送实现

          1. 开通邮箱服务

          使用qq邮箱、163邮箱都行,其他有邮箱服务功能的都可以,这里以163邮箱为例

          登录163邮箱,然后在设置那里选择POP3/SMTP/IMAP

          基于spring boot实现邮箱发送和邮箱验证,在这里插入图片描述,第1张

          开通IMAP/SMTP服务

          基于spring boot实现邮箱发送和邮箱验证,在这里插入图片描述,第2张

          开通后会有个授权码,记录下来,后面需要用到

          基于spring boot实现邮箱发送和邮箱验证,在这里插入图片描述,第3张

          2. 添加邮箱依赖

          添加pom文件

          
              org.springframework.boot
              spring-boot-starter-mail
          
          

          3.添加配置

          host是开通smtp时会有个地址的

          username填的是邮箱账号

          password填的是刚才上面开通smtp的授权码,请注意不是邮箱密码,是授权码

          注:

          1.配置里面有个port的配置是默认端口,尽量不要自己去设置,不然可能会无法访问,以下配置是没有port的

          2.配置错误可以尝试把注释去掉,因为有可能会因为复制过去的编码问题影响

          spring:
           mail:
              host: smtp.163.com # smtp地址,开通的时候会显示
              username: xxxxx@163.com # 你的邮箱账号
              password: ****** # 你的邮箱授权码
              properties:
                mail:
                  smtp:
                    auth: true
                    starttls:
                      enable: true
              protocol: smtp
          

          4.添加邮箱通用类

          这里是用了hutools的工具和lombok的Slf4j日志,视情况而添加

          
          
              cn.hutool
              hutool-all
              5.8.2
          
          
              org.projectlombok
              lombok
              1.18.4
              provided
          
          
          @Service
          @Slf4j
          public class EmailService {
              @Autowired
              private JavaMailSender mailSender;
              @Value("${spring.mail.username}")
              private String username;
              /**
               * 发送文本邮件
               *
               * @param to      收件人地址
               * @param subject 邮件主题
               * @param content 邮件内容
               * @param cc      抄送地址
               */
              public  void sendSimpleMail(String to, String subject, String content, String... cc) {
                  SimpleMailMessage message = new SimpleMailMessage();
                  message.setFrom(username);
                  message.setTo(to);
                  message.setSubject(subject);
                  message.setText(content);
                  if (ArrayUtil.isNotEmpty(cc)) {
                      message.setCc(cc);
                  }
                  mailSender.send(message);
              }
              /**
               * 发送HTML邮件
               *
               * @param to      收件人地址
               * @param subject 邮件主题
               * @param content 邮件内容
               * @param cc      抄送地址
               */
              public  void sendHtmlMail(String to, String subject, String content, String... cc) {
                  try {
                      MimeMessage message = mailSender.createMimeMessage();
                      MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
                      helper.setFrom(username);
                      helper.setTo(to);
                      helper.setSubject(subject);
                      helper.setText(content, true);
                      if (ArrayUtil.isNotEmpty(cc)) {
                          helper.setCc(cc);
                      }
                      mailSender.send(message);
                  } catch (MessagingException e) {
                      log.error("发送邮件失败,收件人:{}", to, e);
                  }
              }
              /**
               * 发送带附件的邮件
               *
               * @param to       收件人地址
               * @param subject  邮件主题
               * @param content  邮件内容
               * @param filePath 附件地址
               * @param cc       抄送地址
               */
              public  void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) {
                  try {
                      MimeMessage message = mailSender.createMimeMessage();
                      MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
                      helper.setFrom(username);
                      helper.setTo(to);
                      helper.setSubject(subject);
                      helper.setText(content, true);
                      if (ArrayUtil.isNotEmpty(cc)) {
                          helper.setCc(cc);
                      }
                      FileSystemResource file = new FileSystemResource(new File(filePath));
                      String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                      helper.addAttachment(fileName, file);
                      mailSender.send(message);
                  } catch (MessagingException e) {
                      log.error("发送邮件失败,收件人:{}", to, e);
                  }
              }
              /**
               * 发送正文中有静态资源的邮件
               *
               * @param to      收件人地址
               * @param subject 邮件主题
               * @param content 邮件内容
               * @param rscPath 静态资源地址
               * @param rscId   静态资源id
               * @param cc      抄送地址
               */
              public  void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) {
                  try {
                      MimeMessage message = mailSender.createMimeMessage();
                      MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
                      helper.setFrom(username);
                      helper.setTo(to);
                      helper.setSubject(subject);
                      helper.setText(content, true);
                      if (ArrayUtil.isNotEmpty(cc)) {
                          helper.setCc(cc);
                      }
                      FileSystemResource res = new FileSystemResource(new File(rscPath));
                      helper.addInline(rscId, res);
                      mailSender.send(message);
                  } catch (MessagingException e) {
                      log.error("发送邮件失败,收件人:{}", to, e);
                  }
              }
          }
          

          5. 测试类

          @RunWith(SpringJUnit4ClassRunner.class)
          @SpringBootTest(classes={EmailServiceApplication.class, EmailServiceTest.class})
          public class EmailServiceTest {
              @Resource
              private EmailService emailService;
              @Test
              public void test(){
                  emailService.sendSimpleMail("1191986647@qq.com","测试","测试");
              }
          }
          

          基于spring boot实现邮箱发送和邮箱验证,在这里插入图片描述,第4张

          二、邮箱验证实现

          实现验证需要使用redis,本章节不介绍如何使用redis,请自行搭建

          1.添加依赖

          
              org.springframework.boot
              spring-boot-starter-data-redis
          
          
          
              redis.clients
              jedis
          
          

          2. 添加配置

          yaml配置

          spring:
            redis:
              host: localhost # redis地址
              port: 6379
              database: 0  
              password: 123456 # 密码,无密码可不填
          

          序列化配置,新建一个config包,并添加RedisConfig类

          @Configuration
          public class RedisConfig {
              @Bean
              public StringRedisTemplate redisTemplate(RedisConnectionFactory factory) {
                  StringRedisTemplate template = new StringRedisTemplate(factory);
                  template.setKeySerializer(new StringRedisSerializer());
                  template.setValueSerializer(new StringRedisSerializer());
                  return template;
              }
          }
          

          3.添加controller

          @RestController
          @RequestMapping("/api")
          public class VerificationController {
              @Autowired
              private EmailService emailService;
              @Autowired
              private StringRedisTemplate redisTemplate;
              @PostMapping("/sendCode")
              public String sendCode(@RequestParam String email) {
                  // 生成验证码
                  String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
                  emailService.sendHtmlMail(email, "【邮箱验证码】欢迎使用xxx系统", "

          您的邮箱验证码是:

          "+code+"

          " ); // 存储验证码到 Redis,设置过期时间为 5 分钟 ValueOperations ops = redisTemplate.opsForValue(); redisTemplate.delete(email); ops.set(email, code, 5, TimeUnit.MINUTES); return "验证码已发送"; } @PostMapping("/verifyCode") public String verifyCode(@RequestParam String email, @RequestParam String code) { // 从 Redis 获取验证码 ValueOperations ops = redisTemplate.opsForValue(); String storedCode = ops.get(email); if (storedCode != null && storedCode.equals(code)) { redisTemplate.delete(email); return "邮箱验证成功"; } else { return "验证码错误或者已失效"; } } }

          4. 测试

          发送

          基于spring boot实现邮箱发送和邮箱验证,在这里插入图片描述,第5张

          基于spring boot实现邮箱发送和邮箱验证,在这里插入图片描述,第6张

          验证

          基于spring boot实现邮箱发送和邮箱验证,在这里插入图片描述,第7张

          基于spring boot实现邮箱发送和邮箱验证,在这里插入图片描述,第8张