用QQ邮箱服务器发送邮件
添加的依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
package com.ql.buy.config;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class EmailStudy {
public static void main(String[] args) {
// 邮件发送配置
String host = "smtp.qq.com"; // SMTP服务器地址
int port = 587; // SMTP端口号
String username = ""; // 发件人邮箱
String password = ""; // 发件人密码或者授权码,授权码的生成往下看
// 邮件内容
String recipient = ""; // 收件人邮箱
String subject = "Test Email"; // 邮件主题
String body = "This is a test email."; // 邮件内容
// 设置SMTP属性
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// 创建会话
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
message.setSubject(subject);
message.setText(body);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
}
如果出现如下报错信息:
javax.mail.AuthenticationFailedException: 535 Login Fail. Please enter your authorization code to login.
解决办法:
登录QQ邮箱,点击【设置】–》【账号】,将服务开启
点击【管理服务】,在新页面点击【前往绑定】,按照提示发送短信把手机号码绑定
绑定后点击【生成授权码】,微信扫码发短信后,会给一个16位长的授权码,用**授权码代替密码**