工具:发送邮箱验证码

549 阅读1分钟

这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战

最近写东西的时候,用到了邮箱验证码,就记录一下自己是怎么写的,别问我为什么不是短信,因为没钱。。其实是我的申请一直过不去,就卡住了。。

接下来,我们步入正题

导入我们需要的依赖

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.5</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-common</artifactId>
            <version>4.1.70.Final</version>
        </dependency>

一个邮箱发送的工具类

@PropertySource("classpath:emailConfig.properties")
public class EmailCode {

    //发送者邮箱,我这里使用的是文件注入的方式,涉及到个人隐私就不展示了
    @Value("${email.sender}")
    private String sender;

    //设置服务器主机
    //连接邮件服务器:邮箱类型,帐号,POP3/SMTP协议授权码 163使用:smtp.163.com
    @Value("${email.host}")
    private String host;

    //授权码
    @Value("${email.SMTP}")
    private String SMTP;



    public void code(String recipient) throws Exception {

        Properties prop = new Properties();
        // 开启debug调试,以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", host);
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        // 开启SSL加密,否则会失败
        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协议授权码
        ts.connect(host, sender, SMTP);
        // 创建邮件
        Message message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress(sender));
        // 指明邮件的收件人,发件人和收件人如果是一样的,那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        // 邮件的标题
        message.setSubject("XXXX");
        
        message.setContent("XXXXXX", "text/html;charset=UTF-8");
        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }

我们需要的参数就是我们的邮箱,调用这个类就可以发送邮件了。

SMTP的获取方式