1.下载jar包
2.将mail.jar 和 activation.jar两个jar包导入项目
3.发送邮件代码如下
public static boolean sendEmail(String to, String title, String content, String from, String key) {
String host = "smtp.qq.com"; // QQ 邮件服务器
Properties properties = System.getProperties();// 获取系统属性
properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf;
try {
sf = new MailSSLSocketFactory();
} catch (GeneralSecurityException e) {
return false;
}
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
// 获取默认session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, key); // 发件人邮件用户名、密码
}
});
try {
MimeMessage message = new MimeMessage(session);// 创建默认的
// MimeMessage对象
message.setFrom(new InternetAddress(from, "测试", "UTF-8"));// Set
// From:头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// Set
// To:头部头字段
message.setSubject(title, "UTF-8");// Set Subject:头部头字段
message.setContent(content, "text/html;charset=UTF-8");// 设置消息体
message.setSentDate(new Date());
Transport.send(message);// 发送消息
} catch (MessagingException | UnsupportedEncodingException mex) {
return false;
}
return true;
}
4.需要导入的包
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
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;
import com.sun.mail.util.MailSSLSocketFactory;