1.首先导入mail.jar和activation.jar包
- 下载点这里*
- 将两个包放到你的JDK下的*\jre\lib\ext*
- 放入后,如果导入不了javax.mail包的,在IDEA中进行如下操作*
File–>Project Structure–>SDKs中,重新选择JDK的安装路径,然后应用就可以了。
2.其次,要打开QQ邮箱的SMTP(简单邮件传输协议),打开QQ邮箱,在设置–》账户
- 开启后,会出现一个授权码,现在不用管,后面会说的。
3.准备好了,可以开始了敲代码了
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) throws MessagingException {
// 创建Properties 类用于记录邮箱的一些属性
Properties properties = new Properties();
// 表示SMTP发送邮件,必须进行身份验证
properties.put("mail.smtp.auth","true");
//此处填写SMTP服务器
properties.put("mail.smtp.host","smtp.qq.com");
//端口号,QQ邮箱端口587
properties.put("mail.smtp.port", "587");
// 此处填写,写信人的账号
properties.put("mail.user","qq邮箱@qq.com");
// qq邮箱产生--授权码
properties.put("mail.password","oomlsulybqaodgej");
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = properties.getProperty("mail.user");
String password = properties.getProperty("mail.password");
return new PasswordAuthentication(userName,password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session session = Session.getInstance(properties,authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(session);
// 设置发件人
InternetAddress from = new InternetAddress(properties.getProperty("mail.user"));
message.setFrom(from);
//收件人
InternetAddress to = new InternetAddress("qq邮箱@qq.com");
message.setRecipient(RecipientType.TO,to);
// 设置邮件标题
message.setSubject("标题");
// 设置邮件的内容体
message.setContent("内容","text/html;charset=UTF-8");
//发送邮件
Transport.send(message);
}
}
这里要注意一下,password要填写授权码,授权码的获得在开启SMTP后,下面会有提示。如果这里写的QQ邮箱密码会报错,SMTP无法连接。
properties.put(“mail.password”,“oomlsulybqaodgej”);