Java发送邮箱验证码

1、开启POP3/SMTP/IMAP

一般在设置中就能找到,开启后会有一串英文记得保存(只能看到这一次1哦),后面会使用
网易邮箱为例:
在这里插入图片描述
qq邮箱为例:
在这里插入图片描述

2、代码实现

以网易邮箱为例
传的参数:MailUtils.sendMail(“接受验证码的邮箱”,验证码);

需要再pom下导入(maven工程),非maven去下载这两个jar包导入即可

<!--邮箱发送-->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>

代码实现如下:

package com.ch.reggie.utils;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 邮箱发送工具类
 */
public class MailUtils {
    /**
     * 发送验证码
     *
     * @param receiveMail
     * @throws Exception
     */
    public static void sendMail(String receiveMail,String verifyCode) {
        Properties prop = new Properties();
        // 开启debug调试,以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.163.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        // 开启SSL加密,否则会失败
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
            // 创建session
            Session session = Session.getInstance(prop);
            // 通过session得到transport对象
            Transport ts = session.getTransport();
            // 连接邮件服务器:邮箱类型,帐号,POP3/SMTP协议授权码 163使用:smtp.163.com,qq使用:smtp.qq.com
            ts.connect("smtp.163.com", "1、开启了POP3/SMTP协议的邮箱号", "2、要你保存的那串英文");
            // 创建邮件
            Message message = createSimpleMail(session, receiveMail,verifyCode);
            // 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @Method: createSimpleMail
     * @Description: 创建一封只包含文本的邮件
     */
    public static MimeMessage createSimpleMail(Session session, String receiveMail,String verifyCode) throws Exception {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("3、发件人邮箱"));
        // 指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveMail));
        // 邮件的标题
        message.setSubject("验证码");
        // 邮件的文本内容
        message.setContent("您的验证码:" + verifyCode + ",如非本人操作,请忽略!请勿回复此邮箱", "text/html;charset=UTF-8");

        // 返回创建好的邮件对象
        return message;
    }
}
### Spring Boot Java 发送邮件验证码并使用 Redis 实现 #### 添加 Maven 依赖 为了在Spring Boot项目中集成Redis和发送邮件功能,需要添加如下Maven依赖: ```xml <dependencies> <!-- Spring Boot Starter Data Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-redis</artifactId> </dependency> <!-- Mail Sender Dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies> ``` 上述配置会自动设置`RedisConnectionFactory`默认采用Lettuce客户端实现[^1]。 #### 配置文件 `application.yml` 确保应用配置文件中有相应的Redis连接参数以及邮箱服务器的相关信息: ```yaml spring: redis: host: localhost port: 6379 mail: server: host: smtp.example.com username: user@example.com password: secretpassword protocol: smtps properties.mail.smtp.auth: true properties.mail.smtp.socketFactory.port: 465 properties.mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory ``` #### 创建服务层用于处理验证码逻辑 创建名为`VerificationCodeService.java`的服务类来负责生成、存储及验证验证码: ```java @Service public class VerificationCodeService { @Autowired private StringRedisTemplate stringRedisTemplate; public void sendEmailWithCode(String email) { // Generate a random verification code (e.g., six digits) Random random = new Random(); int number = random.nextInt(999999); String code = String.format("%06d", number); // Store the generated code into Redis with expiration time of two minutes. stringRedisTemplate.opsForValue().set(email, code, Duration.ofMinutes(2)); // Send an email containing this code to the specified address... EmailUtil.sendSimpleMail(email, "Your verification code is:" + code); } /** * Verify whether the given code matches what was sent earlier and hasn't expired yet. */ public boolean verifyCode(String email, String inputCode){ Object storedCodeObj = stringRedisTemplate.opsForValue().get(email); if(storedCodeObj != null && storedCodeObj.equals(inputCode)){ return true; }else{ return false; } } } ``` 这段代码展示了如何利用`StringRedisTemplate`对象将电子邮件地址作为键名保存六位数的随机码至Redis数据库,并设定其过期时间为两分钟。当用户提交表单时,则可以通过调用`verifyCode()`方法来进行匹配检验。 #### 定义控制器接收前端请求 编写RESTful API端点供外部访问,在这里假设已经实现了简单的邮件发送工具类`EmailUtil`: ```java @RestController @RequestMapping("/api/vc") public class VcController { @Autowired private VerificationCodeService vcService; @PostMapping("/send-email-code") public ResponseEntity<String> handleSendEmail(@RequestParam("email") String email){ try { vcService.sendEmailWithCode(email); return ResponseEntity.ok("Sent successfully"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } } @GetMapping("/validate/{email}/{code}") public ResponseEntity<Boolean> validateCode(@PathVariable String email,@PathVariable String code){ Boolean isValidated = vcService.verifyCode(email,code); return ResponseEntity.ok(isValidated); } } ``` 此部分描述了一个基本的API设计模式,其中包含了两个HTTP POST 和 GET 请求映射分别用来触发向指定电子信箱传送一次性密码的操作以及确认接收到的一次性密码是否正确无误[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值