发送邮箱验证码

/**
 * 邮箱验证码
 *
 * @param userCount 邮箱账号
 * @param response
 */
@RequestMapping("vcode")
public void vcode(String userCount, HttpServletResponse response) throws IOException {
    BackModel result = null;
    String title = "账号注册";
    try {
        if (StringUtils.isEmpty(userCount)) {
            result = new BackModel(0, null, "请输入邮箱账号");
        } else {
            UserInfo userInfo = userInfoService.selectByUserAccount(userCount);
            String code = "";
            for (int i = 0; i < 6; i++) {
                code = code + (int) (Math.random() * 9);
            }
            SendMailUtils.sendMail(userCount, code, title);
            RedisUtils.set(RedisKeys.VCODE + userCount, code, 300);
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            long t1 = System.currentTimeMillis();
            cal.add(Calendar.DATE, 5);
            long t2 = cal.getTimeInMillis();
            long t3 = (t2 - t1) / 1000;
            RedisUtils.set(RedisKeys.VCODE_RECORD + userCount, "", (int) t3);
            result = new BackModel(1, null, "发送成功");
        }
    } catch (Exception e) {
        e.printStackTrace();
        result = new BackModel(0, null, "服务器发生异常");
    } finally {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSON(result).toString());
        response.getWriter().flush();
        response.getWriter().close();
    }
}
public class SendMailUtils {

    private static String  FROM="xxx";// 发件人电子邮箱
    private static String  VCode="1234567";//授权码或者账号密码
    // 方法一:必须要用授权码
    public static void sendMail(String email,String code,String title){
        // 1.创建连接对象javax.mail.Session
        // 2.创建邮件对象 javax.mail.Message
        // 3.发送一封激活邮件
        String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
        Properties properties = System.getProperties();// 获取系统属性
        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证
        try {
            //QQ邮箱需要下面这段代码,163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(FROM, VCode); // 发件人邮箱账号、授权码
                }
            });
            // 2.创建邮件对象
            Message message = new MimeMessage(session);
            // 2.1设置发件人
            message.setFrom(new InternetAddress(FROM));
            // 2.2设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3设置邮件主题
            message.setSubject(title);
            // 2.4设置邮件内容
            String content = "<html><head></head><body><h1>这是一封"+title+"邮件</h1><h3>动态验证码:"
                    + code + " </h3>请在5分钟内完成验证。如非本人操作请忽略。</body></html>";
            message.setContent(content, "text/html;charset=UTF-8");
            // 3.发送邮件
            Transport.send(message);
            System.out.println("邮件成功发送!");
        } catch (Exception e) {
            e.printStackTrace();
        }
   }
}

 //方法二:使用账号 密码

 public static void sendMessage(String email,String code,String title){
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.host", "邮件服务器");
            prop.setProperty("mail.transport.protocol", "smtp");
            prop.setProperty("mail.smtp.auth", "true");
            prop.setProperty("mail.smtp.ssl.enable","true");
            //创建session
            Session session = Session.getInstance(prop);
            //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
            session.setDebug(true);
            //通过session得到transport对象
            Transport ts = session.getTransport();
            //使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
            ts.connect("邮件服务器", "用户名", VCode);
            //创建邮件对象
            MimeMessage message = new MimeMessage(session);
            //指明邮件的发件人
            message.setFrom(new InternetAddress(FROM));
            //指明邮件的收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
            //邮件的标题
            message.setSubject(title);
            //邮件的文本内容
            String content = "<html><head></head><body><h1> This is a"+title+".</h1><h3>Dynamic verification code:"
                    + code + " .</h3>please complete the verification within 5 minutes. Please ignore if you are not operating by yourself.</body></html>";
            message.setContent(content, "text/html;charset=UTF-8");
            //发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
            System.out.println("邮件成功发送!");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

 

在 Spring Boot 中发送邮箱验证码可以通过使用 JavaMailSender 来实现。首先,你需要在 `application.properties` 或 `application.yml` 配置文件中配置邮件服务器的相关信息,如下所示: application.properties: ```properties spring.mail.host=your.mail.server spring.mail.port=your.mail.port spring.mail.username=your.username spring.mail.password=your.password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` application.yml: ```yaml spring: mail: host: your.mail.server port: your.mail.port username: your.username password: your.password properties: mail: smtp: auth: true starttls: enable: true ``` 接下来,你可以创建一个邮件服务类来发送验证邮件,示例如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender javaMailSender; public void sendVerificationCode(String to, String code) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject("验证码"); message.setText("您的验证码是:" + code); javaMailSender.send(message); } } ``` 在上述示例中,`JavaMailSender` 是由 Spring Boot 自动配置的邮件发送器。你可以在需要发送验证码的地方调用 `sendVerificationCode` 方法来发送邮件。 注意:为了使用JavaMailSender,你需要在项目的依赖管理文件(例如 pom.xml)中添加相应的依赖。你可以添加以下依赖来使用 Spring Boot 提供的邮件支持: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 以上就是使用 Spring Boot 发送邮箱验证码的简单示例。你可以根据自己的实际需求进行调整和扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值