JAVA利用MimeMessage实现发送验证码

237 阅读2分钟

写这个是因为接口忘记密码,需要发送邮件到用户邮箱

语言:Java 软件:idea 项目:springBoot maven 使用发件的邮箱:QQ邮箱

逻辑:根据随机数生成密码,发送邮件,并将验证码和邮箱,状态,时间存储到数据库,核验的时候查最新的一条,此项目发送验证码有两种,注册和修改密码

1,首先我们需要在pom.xml添加

 <!-- 邮件 -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.5.6</version>
        </dependency>

2,先看前端给我们的数据

email是收件人邮箱,type表示是注册还是忘记密码,pwd是忘记密码

3,看controller层

  //发送验证码邮件
    @PassToken
    @PostMapping("/api/index/sendEmailCode")
    public ResultData sendRandom(String email,String type)throws GeneralSecurityException, MessagingException {
        String title = "【GrillAid App】";
        String code = addRandom();
        String text = "Dear user <br>" +
                "Your verification code is:"+
                "\n" +
                code+
                "<br>" +
                "Yours sincerely!<br>" +
                "GrillAid";
        //发送邮件
        send(title,text,email);
        ToCode toCode = new ToCode();
        toCode.setCode(code);
        toCode.setEmail(email);
        toCode.setType(type);
        long timeStampSec = System.currentTimeMillis()/1000;
        String timestamp = String.format("%010d", timeStampSec);
        toCode.setTime(timestamp);
        codeService.insertToCode(toCode);//存储验证码缓存
        return ResultData.success();
    }



    //生成随机数
    public String addRandom(){
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
       return result;
    }

4,看我们的邮件发送class

package com.ruoyi.app.controller.system.controller;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class SendEamil {

    public static void send(String title,String text,String email)throws MessagingException, GeneralSecurityException {
        //创建一个配置文件并保存
        Properties properties = new Properties();

        properties.setProperty("mail.host","smtp.qq.com");

        properties.setProperty("mail.transport.protocol","smtp");

        properties.setProperty("mail.smtp.auth","true");


        //QQ存在一个特性设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("发件人邮箱","16位授权码");
            }
        });

        //开启debug模式
        session.setDebug(true);

        //获取连接对象
        Transport transport = session.getTransport();

        //连接服务器
        transport.connect("smtp.qq.com","发件人邮箱","16位授权码");

        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);

        //邮件发送人
        mimeMessage.setFrom(new InternetAddress("发件人 邮箱"));

        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(email));

        //邮件标题
        mimeMessage.setSubject(title);

        //邮件内容
        mimeMessage.setContent(text,"text/html;charset=UTF-8");

        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        //关闭连接
        transport.close();
    }
}

原本以为很难的发送邮件就这样完成啦★,°:.☆( ̄▽ ̄)/$:.°★ 。 感谢您的耐心地看到最后。