发送邮件需要有JavaMail API,并且需要安装JavaBean Activation Framework,所以需要下载两个jar包mail.jar和activation.jar,下面给出官网下载地址
mail.jar:http://www.oracle.com/technetwork/java/javamail/index.html
activation.jar:http://www.oracle.com/technetwork/articles/java/index-135046.html
将两个jar包添加到我们的项目中,下面是Java代码:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
String result;
// 收件人的电子邮件
String to = "收件人邮箱地址";
// 发件人的电子邮件
String from = "发件人邮箱地址";
// 发送电子邮件主机
String host = "smtp.qq.com";
// 获取系统属性对象
final Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.user", "发件人邮箱地址");
properties.setProperty("mail.password", "发件人邮箱授权码");
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = properties.getProperty("mail.user");
String password = properties.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 获取默认的Session对象。
Session mailSession = Session.getInstance(properties, authenticator);
try {
// 创建一个默认的MimeMessage对象。
MimeMessage message = new MimeMessage(mailSession);
// 设置 From: 头部的header字段
message.setFrom(new InternetAddress(from));
// 设置 To: 头部的header字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
// 设置 Subject: header字段
message.setSubject("邮箱验证码");
// 现在设置的实际消息
message.setText("验证码为:123");
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
System.out.println("Error: unable to send message....");
}
}
}
1、设置密码时,是设置授权码,不是邮箱登录密码。如果设置为登录密码会报password相关的错误。邮箱授权默认关闭,在邮箱设置菜单里面打开授权获取授权码
2、邮箱安全等级设置低,一般设置为默认
3、QQ会员邮箱发送不出邮件,博主猜测QQ会员有可能安全级别比较高,所以系统会判断为垃圾邮件自动屏蔽,不报错也发送不出去
4、授权码设置成功后,有可能不会立马生效,过一会再试
5、以上几点异常是开发的过程中碰到的,还有其它请知会学习,谢谢!