首先来到自己的邮箱,点击设置

image-20220808182157154

点击账户

image-20220808182222909

下滑,这里点击开启

image-20220808182252594

发送短信验证

image-20220808182307112

然后就会得到授权码,将其保存起来

image-20220808182446619

然后导入依赖

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>

然后是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", "xxx@qq.com");
        // 此处填写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("xxxx@qq.com");
        message.setRecipient(MimeMessage.RecipientType.TO, to);

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

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

        // 发送
        Transport.send(message);

    }
}