java向QQ邮箱发送验证码

准备环境
java向QQ邮箱发送验证码_第1张图片

java向QQ邮箱发送验证码_第2张图片

java向QQ邮箱发送验证码_第3张图片
java向QQ邮箱发送验证码_第4张图片

发送完后会得到一串码保存下来
在pom.xml中导入依赖,如果当前版本太老可以 https://mvnrepository.com/ 到maven仓库中找javax.mail


    com.sun.mail
    javax.mail
    1.6.2


    javax.mail
    javax.mail-api
    1.6.2



```java
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class sendEmail {
    public static void send_QQ(String code) throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.port", "587");
        // 此处填写,写信人的账号
        props.put("mail.user", "[email protected]");
        // 此处填写16位STMP口令,刚刚复制的字符串
        props.put("mail.password", "xxx");

        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        Session mailSession = Session.getInstance(props, authenticator);
        MimeMessage message = new MimeMessage(mailSession);
        InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
        message.setFrom(form);

        // 设置收件人的邮箱
        InternetAddress to = new InternetAddress("[email protected]");
        message.setRecipient(MimeMessage.RecipientType.TO, to);

        // 设置邮件标题
        message.setSubject("验证号码测试");

        // 设置邮件的内容体
        message.setContent(code, "text/html;charset=UTF-8");

        // 发送
        Transport.send(message);

    }
}

你可能感兴趣的:(java)