首先来到自己的邮箱,点击设置
点击账户
下滑,这里点击开启
发送短信验证
然后就会得到授权码,将其保存起来
然后导入依赖
1 | <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);
}
}