基于spring boot实现邮箱发送和邮箱验证

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

一、邮箱发送实现

1. 开通邮箱服务

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

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

在这里插入图片描述

开通IMAP/SMTP服务

在这里插入图片描述

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

在这里插入图片描述

2. 添加邮箱依赖

添加pom文件

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

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日志,视情况而添加

<!-- 工具类 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.2</version>
</dependency>


<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
    <scope>provided</scope>
</dependency>
@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","测试","测试");
    }
}

在这里插入图片描述

二、邮箱验证实现

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

1.添加依赖

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

<!-- jedis连接 -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

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系统", "<p>您的邮箱验证码是:<p><p style=\" font-weight: bold;text-align: center;color: red;\">"+code+"</p>" );
        // 存储验证码到 Redis,设置过期时间为 5 分钟
        ValueOperations<String, String> 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<String, String> ops = redisTemplate.opsForValue();
        String storedCode = ops.get(email);

        if (storedCode != null && storedCode.equals(code)) {
   
            redisTemplate.delete(email);
            return "邮箱验证成功";
        } else {
   
            return "验证码错误或者已失效";
        }
    }
}

4. 测试

发送

在这里插入图片描述

在这里插入图片描述

验证

在这里插入图片描述
在这里插入图片描述

相关推荐

  1. springboot发送邮件

    2024-02-01 11:52:02       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-01 11:52:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-01 11:52:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-01 11:52:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-01 11:52:02       18 阅读

热门阅读

  1. React和Vue实现路由懒加载

    2024-02-01 11:52:02       26 阅读
  2. SpringCloud

    2024-02-01 11:52:02       37 阅读
  3. 大数据之 Spark 比 MapReduce 快的原因

    2024-02-01 11:52:02       32 阅读
  4. Springboot项目多数据源配置详细步骤

    2024-02-01 11:52:02       32 阅读
  5. 幻兽帕鲁服务器游戏版本怎么升级更新?

    2024-02-01 11:52:02       33 阅读
  6. 低代码开发在金融系统中的应用研究

    2024-02-01 11:52:02       42 阅读
  7. 【Linux 无网络状态下离线安装 MySQL】

    2024-02-01 11:52:02       38 阅读
  8. vue3兼容超宽屏、超窄屏、4K屏幕等等

    2024-02-01 11:52:02       31 阅读
  9. API横向越权修复之ID加密

    2024-02-01 11:52:02       26 阅读