public class MailUtils implements Runnable{
final String sendEmail = "www.123.com";
final String emailUser = "www.123456.com";
final String emailPassword = "111111";
private String email; //接收邮箱
private String title;//邮件主题
private String content;//邮箱内容
public MailUtils(String email, String title, String content) {
this.email = email;
this.title = title;
this.content = content;
}
public void run() {
// 配置
Properties prop = new Properties();
// 设置邮件服务器主机名,这里是163
prop.put("mail.host", "smtp.263.net");
// 发送邮件协议名称
prop.put("mail.transport.protocol", "smtp");
// 是否认证
prop.put("mail.smtp.auth", true);
try {
// SSL加密
MailSSLSocketFactory sf = null;
sf = new MailSSLSocketFactory();
// 设置信任所有的主机
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
// 创建会话对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
// 认证信息,需要提供"用户账号","授权码"
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailUser, emailPassword);
}
});
// 是否打印出debug信息
session.setDebug(true);
// 创建邮件
Message message = new MimeMessage(session);
// 邮件发送者
message.setFrom(new InternetAddress(sendEmail));
// 邮件接受者
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 邮件主题
message.setSubject(title);
message.setContent(content, "text/html;charset=UTF-8");
// 邮件发送
Transport transport = session.getTransport();
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
transport.close();
LogMgr.sysInfo("邮件发送成功:邮件接收者【" + email + "】,邮件内容【" + content + "】");
} catch (Exception e) {
LogMgr.error("邮件发送失败:", e);
}
}
}