首先将两个文件添加至classpath
文件
activation.jar
mail.jar
代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.List;
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;
/**
* 发送邮件
* @param email
* @throws GeneralSecurityException
*/
public static void senEmail(Emailinfo email) throws GeneralSecurityException {
// 收件人电子邮箱
String to = email.ShouEmail;
// 发件人电子邮箱
String from = email.FaEmail;
// 指定发送邮件的主机 QQ邮箱:smtp.qq.com
String host = email.Host;
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
properties.put("mail.smtp.auth", "true");
//发送邮箱的账号和密码
properties.setProperty("mail.user", email.FaEmail);
properties.setProperty("mail.password", email.emailpassword);
// 获取默认session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,email.code);
}
});
try{
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(from));
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: 头部头字段
message.setSubject(email.setSuject);
// 设置消息体
message.setText(email.setText);
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
//email实体类
public class Emailinfo {
//收件邮箱
public String ShouEmail;
//发送邮箱
public String FaEmail;
//发送服务器ip
public String Host;
//标题
public String setSuject;
//内容
public String setText;
/**
* 授权码 在QQ邮箱获得
*/
public String code;
//用户密码
public String emailpassword;
}
注: 我这是使用的QQ邮箱 所以需要在QQ邮箱内 打开POP3/SMTP服务 并获得授权码
位置:设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务