通过邮件服务器简易实现Java中的邮件发送功能。
1.创建报警信息实体类
public class WarnMesssgeData {
/**
* 预警标题
*/
private String subject;
/**
* 预警内容
*/
private String content;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
2.发送邮件设置
public static void sendEmail(WarnMesssgeData warnMes) throws GeneralSecurityException, MessagingException {
Properties prop = new Properties();
// 开启debug调试,以便在控制台查看
prop.setProperty(“mail.debug”, “true”);
// 设置邮件服务器主机名
prop.setProperty(“mail.host”, “smtp.exmail.qq.com”);
// 发送服务器需要身份验证
prop.setProperty(“mail.smtp.auth”, “true”);
// 发送邮件协议名称
prop.setProperty(“mail.transport.protocol”, “smtp”);
//端口
prop.setProperty(“mail.smtp.port”, “465”);
// 开启SSL加密,否则会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put(“mail.smtp.ssl.enable”, “true”);
prop.put(“mail.smtp.ssl.socketFactory”, sf);
// 创建session
Session session = Session.getInstance(prop);
// 通过session得到transport对象
Transport ts = session.getTransport();
// 连接邮件服务器:邮箱类型,帐号,授权码代替密码(更安全)
ts.connect(“smtp.exmail.qq.com”,“test1@qq.net”, “111111”);
// 创建邮件
InternetAddress[] receiverArr={new InternetAddress(“test1@qq.net”),new InternetAddress(“test2@qq.net”)};
javax.mail.Message message = createMail(session,receiverArr,warnMes);
// 发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
3.生成发送邮件
public static MimeMessage createMail(Session session, InternetAddress[] receiverArr, WarnMesssgeData warnMes) throws MessagingException {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress(“test1@qq.net”));
// 指明邮件的收件人
message.setRecipients(javax.mail.Message.RecipientType.TO, receiverArr);
// 邮件的标题
message.setSubject(warnMes.getSubject());
// 邮件的文本内容
message.setContent(warnMes.getContent(), “text/html;charset=UTF-8”);
// 邮件的创建时间
message.setSentDate(new Date());
// 返回创建好的邮件对象
return message;
}
4.触发发送邮件的方法
public void checkWarn(OperLog operLog) throws MessagingException, GeneralSecurityException {
//符合条件时触发
if (“2”.equals(operLog.getPassFlag())) {
//预警邮件
WarnMesssgeData warnMes = new WarnMesssgeData();
//邮件标题
warnMes.setSubject(“测试NG预警”);
//邮件内容
String content = “连续测试NG预警!”;
warnMes.setContent(content);
KanbanDataTransTask.sendEmail(warnMes);
}
}