实战总结:Java实现邮箱发送验证码

Java邮箱发送验证码

目前项目中需要同时支持短信和邮箱验证,短信用的是腾讯云就不多说了,在此分享一下邮箱验证码发送。
首先,作为发送邮箱,需要开启POP3/SMTP/IMAP,登录邮箱–设置–账户–开启POP3/SMTP/IMAP,开启时可能会有短信验证,开启后显示验证码之类的一串英文,复制保存起来,后面要用。这里以163邮箱为例,其他邮箱操作类似
在这里插入图片描述
开启之后就可以作为发送邮箱,发验证码给用户了,代码如下
pom包引入:

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

邮箱发送工具类:

package com.es.biz.common.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 {
    public static void main(String[] args) {
        sendMail("123@163.com");
    }

    /**
     * 发送验证码
     *
     * @param receiveMail 邮件接收者
     * @throws Exception
     */
    public static void sendMail(String receiveMail) {
        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", "邮件发出者", "上面保存的验证码(一串英文)");
            // 创建邮件
            Message message = createSimpleMail(session, receiveMail);
            // 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @Method: createSimpleMail
     * @Description: 创建一封只包含文本的邮件
     */
    public static MimeMessage createSimpleMail(Session session, String receiveMail) throws Exception {
        //  获取6位随机验证码(英文)
      	String[] letters = new String[]{
                "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m",
                "A", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M",
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(letters[(int) Math.floor(Math.random() * letters.length)]);
        }
        
		//获取6位随机验证码(中文),根据项目需要选择中英文
		String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
		
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("邮件发出者"));
        // 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveMail));
        // 邮件的标题
        message.setSubject("验证码");
        // 邮件的文本内容
        message.setContent("您的验证码:" + verifyCode + ",如非本人操作,请忽略!请勿回复此邮箱", "text/html;charset=UTF-8");

        // 返回创建好的邮件对象
        return message;
    }
}
  • 11
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
要使用 Java 发送邮件验证码,需用到 Java Mail API 库。以下是发送邮件验证码的基本步骤: 1. 确定发件人、收件人、SMTP 服务器地址和端口号; 2. 创建 JavaMail Session 对象,并设置发件人身份验证信息; 3. 使用 JavaMail Session 对象创建一个邮件消息; 4. 设置邮件消息的内容、主题、收发件人等信息; 5. 发送邮件消息。 具体实现代码可以参考以下示例代码: ```java import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public static void main(String[] args) { // 发件人信息 String from = "your_email@example.com"; String password = "your_email_password"; // 收件人信息 String to = "recipient_email@example.com"; // SMTP 服务器信息 String host = "smtp.example.com"; int port = 587; // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.port", port+""); properties.setProperty("mail.smtp.auth", "true"); properties.setProperty("mail.smtp.starttls.enable", "true"); // 获取默认会话对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建邮件消息 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(from)); // 设置收件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置邮件主题 message.setSubject("验证码"); // 生成随机验证码 int code = (int)(Math.random() * 9000 + 1000); // 设置邮件内容 message.setText("您的验证码是:" + code); // 发送邮件 Transport.send(message); System.out.println("邮件已发送。"); } catch (MessagingException e) { System.out.println("发送邮件出现异常:" + e.getMessage()); } } } ``` 以上代码以 Gmail SMTP 服务器为例,需要将 `smtp.example.com` 和端口号 `587` 修改为相应的 SMTP 服务器地址和端口号。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值