现在项目上线一段时间了,希望能够在项目中出现异常后邮件通知给相关开发人员。我从网上找了大量的第三方接口(需要花钱)和发送邮件demo。最后选择了一个只需要引入一个jar包和一个工具类的实现,不需要配置文件,具体的工具类代码如下:
package com.evan.mail;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
MessageVo mv = new MessageVo();
mv.setSubject("很遗憾,您的程序出bug了"+new Date());
mv.setText("bug的具体内容为:"+"空指针异常");
mv.setToMailAddress("zhanglong@jijiankang.cn");
sendMail(mv);
}
public static void sendMail(MessageVo mv ){
final String username = "13641329385@163.com";
final String password = "evan0202";
boolean isSSL = true;
String host = "smtp.163.com";
int port = 465;
boolean isAuth = true;
String from = "13641329385@163.com";
Properties props = new Properties();
props.put("mail.smtp.ssl.enable", isSSL);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", isAuth);
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setSubject(mv.getSubject());
message.setText(mv.getText());
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mv.getToMailAddress()));
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("发送完毕!");
}
}
需要注意的是:
1、发件人邮箱没有开通pop3/SMTP协议需要开通
2、发件人163邮件发送次数多了,163会提示说账号有安全威胁之类,需要你在163邮箱设置授权
3、项目中需要用到的jar是mail-1.4.5.jar
直接将项目导入eclipse,运行main方法即可完成发送邮件
完整项目下载地址(免积分):http://download.csdn.net/download/zl544434558/9393226
原文:http://blog.csdn.net/zl544434558/article/details/50470528