25.4.6学习总结

 邮箱验证码的实现:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class EmailSender {
    // 配置参数(根据你的邮箱修改)
    private static final String FROM = "[email protected]";  // 发件人邮箱
    private static final String PASSWORD = "your_authorization_code"; // 邮箱授权码
    private static final String HOST = "smtp.qq.com"; // SMTP服务器地址
    
    public static void sendVerificationCode(String toEmail) throws MessagingException {
        // 1. 配置参数
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", "465"); // SSL端口
        props.put("mail.smtp.ssl.enable", "true"); // 启用SSL
        props.put("mail.smtp.auth", "true"); // 需要认证
        
        // 2. 创建Session对象
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, PASSWORD);
            }
        });
        
        // 3. 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 设置发件人
        message.setFrom(new InternetAddress(FROM));
        // 设置收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        // 设置邮件主题
        message.setSubject("验证码邮件");
        
        // 生成6位随机验证码
        String verificationCode = generateVerificationCode();
        
        // 设置邮件正文
        String content = "您的验证码是:" + verificationCode + ",有效期5分钟";
        message.setText(content);
        
        // 4. 发送邮件
        Transport.send(message);
        
        System.out.println("邮件发送成功!");
    }
    
    // 生成6位随机验证码
    private static String generateVerificationCode() {
        return String.format("%06d", (int)(Math.random() * 1000000));
    }

    public static void main(String[] args) {
        try {
            sendVerificationCode("[email protected]"); // 测试发送
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}


代码逐行解析

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
    // 配置参数(类级别常量)
    private static final String FROM = "[email protected]";   // 发件人邮箱
    private static final String PASSWORD = "your_authorization_code"; // 邮箱授权码
    private static final String HOST = "smtp.qq.com"; // SMTP服务器地址

作用

  • 定义邮件服务器的连接参数

  • FROM:发件人身份标识

  • PASSWORD:邮箱的授权凭证(注意不是登录密码)

  • HOST:邮件服务提供商的SMTP服务器地址

举一反三

  • 如果使用其他邮箱服务(如163、Gmail),需修改HOST为对应的SMTP地址

  • 敏感信息建议通过配置文件读取(如config.properties


public static void sendVerificationCode(String toEmail) throws MessagingException {
    // 1. 配置网络参数
    Properties props = new Properties();
    props.put("mail.smtp.host", HOST);        // 指定SMTP服务器
    props.put("mail.smtp.port", "465");       // SSL加密端口
    props.put("mail.smtp.ssl.enable", "true");// 启用SSL加密
    props.put("mail.smtp.auth", "true");      // 需要身份验证

作用

  • 创建Properties对象存储邮件服务器配置

  • mail.smtp.host:指定邮件传输协议服务器

  • mail.smtp.port:使用SSL加密时的标准端口

  • mail.smtp.auth:启用身份验证机制

举一反三

  • 非SSL连接时可使用端口25,但安全性较低

  • Gmail可能需要设置mail.smtp.starttls.enable=true


// 2. 创建邮件会话
    Session session = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(FROM, PASSWORD);
        }
    });

作用

  • 通过Session对象建立与邮件服务器的会话

  • 使用匿名内部类实现Authenticator,提供邮箱认证信息

  • PasswordAuthentication封装账号密码

举一反三

  • 可配置session.setDebug(true)开启调试模式,查看SMTP协议交互过程

  • 对于需要多次发送的场景,可复用同一个Session对象提高效率


// 3. 构建邮件内容
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(FROM)); // 设置发件人
    message.setRecipient(Message.RecipientType.TO, 
        new InternetAddress(toEmail)); // 设置收件人
    message.setSubject("验证码邮件"); // 邮件主题
    
    String verificationCode = generateVerificationCode(); // 生成验证码
    message.setText("您的验证码是:" + verificationCode); // 邮件正文

作用

  • MimeMessage表示一封电子邮件的完整结构

  • setRecipient支持多种类型:TO(主送)、CC(抄送)、BCC(密送)

  • setText设置纯文本内容

举一反三

  • 添加多个收件人:

    message.addRecipient(Message.RecipientType.CC, 
        new InternetAddress("[email protected]"));
  • 发送HTML内容:

    message.setContent("

    验证码

    ", "text/html");

// 4. 发送邮件
    Transport.send(message);
    System.out.println("邮件发送成功!");
}

作用

  • Transport类负责实际发送操作

  • 发送完成后输出成功提示

举一反三

  • 可添加重试机制:

    int retry = 3;
    while(retry-- > 0) {
        try {
            Transport.send(message);
            break;
        } catch (Exception e) {
            if(retry == 0) throw e;
        }
    }

验证码生成方法

private static String generateVerificationCode() {
    return String.format("%06d", (int)(Math.random() * 1000000));
}

作用

  • 生成6位数字验证码

  • Math.random()生成0-1之间的随机数

  • String.format确保不足6位时前面补零

举一反三

  • 生成字母数字混合验证码:

    String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    StringBuilder code = new StringBuilder();
    for(int i=0; i<6; i++) {
        code.append(chars.charAt((int)(Math.random()*chars.length())));
    }
    return code.toString();

你可能感兴趣的:(学习)