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