public class Sendmail { private static final Log logger = LogFactory.getLog(Sendmail.class);
public static Map<String,Object> sendTextMail(String strMail, String strTitle, String strText){ Map<String,Object> map = new HashMap<String, Object>(); String sends=null; Properties prop = new Properties(); // 开启debug调试,以便在控制台查看 prop.setProperty("mail.debug", "true"); // 设置邮件服务器主机名 prop.setProperty("mail.host", "smtp.qq.com"); // 发送服务器需要身份验证 prop.setProperty("mail.smtp.auth", "true"); // 发送邮件协议名称 prop.setProperty("mail.transport.protocol", "smtp");
// 开启SSL加密,否则会失败 try { 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.qq.com","****", "mddbpoilzjhidcjh");//后面的字符是授权码 // 创建邮件 MimeMessage message = new MimeMessage(session); // 指明邮件的发件人 message.setFrom(new InternetAddress("*****@qq.com")); // 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发 message.setRecipient(Message.RecipientType.TO, new InternetAddress(strMail)); // 邮件的标题 message.setSubject(strTitle); // 邮件的文本内容 message.setContent("<font style=‘color:red‘>"+strText+"</font>", "text/html;charset=UTF-8"); // 发送邮件 ts.sendMessage(message, message.getAllRecipients()); ts.close(); } catch (Exception e) { logger.error("发送邮件异常"); return (Map<String, Object>) map.put(sends, "发送邮件异常"); }
return (Map<String, Object>) map.put(sends, "发送邮件成功"); }
/* public static void main(String[] args) { try { Sendmail.sendTextMail("****@163.com","日志容量告警","测试邮件发送"); } catch (Exception e) { // TODO: handle exception }
}*/ }
|