1.完整代码示例
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class MailSmsUtil {
private static final String username = "你的账号";
private static final String password = "你的密码";
private static final String theme = "邮件主题";
// 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)|smtp.mxhichina.com(阿里)
private static final String hosts = "smtp.mxhichina.com";
public static void send(String email, String code) {
// 1.创建连接对象javax.mail.Session
// 2.创建邮件对象 javax.mail.Message
// 3.发送一封激活邮件
String from = username;// 发件人电子邮箱
String host = hosts; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
Properties properties = System.getProperties();// 获取系统属性
properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
properties.setProperty("mail.smtp.auth", "true");// 打开认证
try {
//QQ邮箱需要下面这段代码,163邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
// 1.获取默认session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password); // 发件人邮箱账号、授权码
}
});
// 2.创建邮件对象
Message message = new MimeMessage(session);
// 2.1设置发件人
message.setFrom(new InternetAddress(from);
// 2.2设置接收人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 2.3设置邮件主题
message.setSubject(theme);
// 2.4设置邮件内容
String content = "<html><head></head><body>验证码:"+code+",请妥善保管,切勿泄露</body></html>";
message.setContent(content, "text/html;charset=UTF-8");
// 3.发送邮件
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.设置发件人名称
// 2.1设置发件人
message.setFrom(new InternetAddress(from,"发件人名称","utf-8"));
3.QQ 邮箱需要在 设置->账户里开启 SMTP 服务
注意开启完之后,QQ 邮箱会生成一个授权码,在代码里连接邮箱使用这个授权码而不是原始的邮箱密码,这样可以避免使用明文密码。