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 }
}*/ }
|