package com.sf.novatar.plf.utils; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeUtility; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.mail.Email; import org.apache.commons.mail.MultiPartEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sf.novatar.context.AppContext; import com.sf.novatar.plf.bean.MailCommBean; public class MailCommon extends Exception { /** * */ private static final long serialVersionUID = 768194185976826713L; private final static Logger logger = LoggerFactory.getLogger(MailCommon.class); final public static int SIMPLE_MAIL = 0; final public static int MUTIL_MAIL = 1; /** 发件方式 - 普通发送 */ final public static int TO = 0; /** 发件方式 - 抄送 */ final public static int CC = 1; /** 发件方式 - 抄送人邮件地址 */ private String addChaoSong = null; /** 发件方式 - 密件抄送 */ final public static int BCC = 2; private int mailType = 0; /** 邮件内容 */ private String mailContent = null; /** 邮件相关信息 - SMTP 服务器 */ private String mailSMTPHost = null; private String mailSMTPHostPort = "25"; /** 邮件相关信息 - 邮件用户名 */ private String mailUser = null; /** 邮件相关信息 - 密码 */ private String mailPassword = null; /** 邮件相关信息 - 发件人邮件地址 */ private String mailFromAddress = null; /** 邮件相关信息 - 邮件主题 */ private String mailSubject = ""; /** 邮件相关信息 - 邮件发送地址 */ private String[] mailTOAddress = null; /** 邮件相关信息 - 邮件抄送地址 */ private String[] mailCCAddress = null; /** 邮件相关信息 - 邮件密件抄送地址 */ private String[] mailBCCAddress = null; /** 邮件相关信息 - 邮件正文(复合结构) */ private javax.mail.internet.MimeMultipart mailBody = null; private MultiPartEmail mailclass = null; private boolean debug = false; private boolean result = false; /** 邮件相关信息 - 邮件發送方顯示名 */ private String mailShowName = "SF Express"; private Log log = LogFactory.getLog(MailCommon.class); public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public MailCommon() { mailBody = new javax.mail.internet.MimeMultipart(); } /** * 设置 SMTP 服务器 * * @param strSMTPHost * 邮件服务器名称或 IP * @param strUser * 邮件用户名 * @param strPassword * 密码 */ public void setSMTPHost(String strSMTPHost, String port, String strUser, String strPassword) { this.mailSMTPHost = strSMTPHost; this.mailUser = strUser; this.mailPassword = strPassword; if (port != null && !port.equals("")) { this.mailSMTPHostPort = port; } } /** * 设置邮件发送地址 * * @param strFromAddress * 邮件发送地址 */ public void setFromAddress(String strFromAddress) { this.mailFromAddress = strFromAddress; } /** * 设置邮件发送地址 * * @param strFromAddress * 邮件发送地址 * @param mailShowName * 邮件顯示名 */ public void setFromAddress(String strFromAddress, String mailShowName) { this.mailFromAddress = strFromAddress; this.mailShowName = mailShowName; } /** * 设置邮件目的地址 * * @param strAddress * 邮件目的地址列表, 不同的地址可用;号分隔 * @param iAddressType * 邮件发送方式 (TO 0, CC 1, BCC 2) 常量已在本类定义 * @throws AddressException */ public void setAddress(String strAddress, int iAddressType) throws Exception { String[] mailAddr = strAddress.split(","); switch (iAddressType) { case MailCommon.TO: { mailTOAddress = mailAddr; break; } case MailCommon.CC: { mailCCAddress = mailAddr; break; } case MailCommon.BCC: { mailBCCAddress = mailAddr; break; } } } /** * 设置邮件主题 * * @param strSubject * 邮件主题 */ public void setSubject(String strSubject) { this.mailSubject = strSubject; } /** * 设置邮件文本正文 * * @param strTextBody * 邮件文本正文 * @throws MessagingException */ public void setTextBody(String strTextBody) throws Exception { MimeBodyPart mimebodypart = new MimeBodyPart(); mimebodypart.setText(strTextBody, "UTF-8"); mailBody.addBodyPart(mimebodypart); mailContent = strTextBody; } /** * 设置邮件超文本正文 * * @param strHtmlBody * 邮件超文本正文 * @throws MessagingException */ public void setHtmlBody(String strHtmlBody) throws Exception { MimeBodyPart mimebodypart = new MimeBodyPart(); mimebodypart.setDataHandler(new DataHandler(strHtmlBody, "text/html;charset=UTF-8")); mailBody.addBodyPart(mimebodypart); mailContent = strHtmlBody; } /** * 设置邮件正文外部链接 URL, 信体中将包含链接所指向的内容 * * @param strURLAttachment * 邮件正文外部链接 URL * @throws MessagingException * @throws MalformedURLException */ public void setURLAttachment(String strURLAttachment) throws Exception { MimeBodyPart mimebodypart = new MimeBodyPart(); mimebodypart.setDataHandler(new DataHandler(new URL(strURLAttachment))); mailBody.addBodyPart(mimebodypart); this.mailType = MUTIL_MAIL; } /** * 设置邮件附件 * * @param strFileAttachment * 文件的全路径 * @throws MessagingException * @throws UnsupportedEncodingException */ public void setFileAttachment(String strFileAttachment) throws Exception { File path = new File(strFileAttachment); if (!path.exists() || path.isDirectory()) { throw new Exception("文件不存在!"); } String strFileName = path.getName(); MimeBodyPart mimebodypart = new MimeBodyPart(); mimebodypart.setDataHandler(new DataHandler(new FileDataSource( strFileAttachment))); mimebodypart.setFileName(MimeUtility.encodeText(strFileName)); mailBody.addBodyPart(mimebodypart); this.mailType = MUTIL_MAIL; } /** * 设置邮件图片附件 * * @param strFileAttachment * 文件的全路径 * @throws MessagingException * @throws UnsupportedEncodingException */ public void setImgFileAttachment(String strFileAttachment, String fileNum) throws Exception { File path = new File(strFileAttachment); if (!path.exists() || path.isDirectory()) { throw new Exception("文件不存在!"); } String strFileName = path.getName(); MimeBodyPart mimebodypart = new MimeBodyPart(); mimebodypart.setDataHandler(new DataHandler(new FileDataSource( strFileAttachment))); mimebodypart.setFileName(MimeUtility.encodeText(strFileName)); mailBody.setSubType("related"); mimebodypart.setHeader("Content-ID", "IMG" + fileNum); mailBody.addBodyPart(mimebodypart); this.mailType = MUTIL_MAIL; } /** * 邮件发送(一次发送多个地址, 优点速度快, 但是有非法邮件地址时将中断发送操作) * * @throws MessagingException */ public void sendBatch() throws Exception { mailclass = new MultiPartEmail(); mailclass.setDebug(this.debug); try{ if (mailTOAddress != null) { for (int i = 0; i < this.mailTOAddress.length; i++) { mailclass.addTo(mailTOAddress[i]); } } if (mailCCAddress != null) { for (int i = 0; i < this.mailCCAddress.length; i++) { mailclass.addCc(mailCCAddress[i]); } } if (mailBCCAddress != null) { for (int i = 0; i < this.mailBCCAddress.length; i++) { mailclass.addBcc(mailBCCAddress[i]); } } mailclass.setHostName(this.mailSMTPHost); mailclass.setSmtpPort(Integer.parseInt(this.mailSMTPHostPort)); //設置郵箱显示名 if(this.mailShowName != null ){ mailclass.setFrom(this.mailFromAddress, this.mailShowName); }else{ mailclass.setFrom(this.mailFromAddress, this.mailUser); } //设置是否验证用户名和密码 // mailclass.setAuthentication(this.mailUser, this.mailPassword); mailclass.setSubject(this.mailSubject); if (SIMPLE_MAIL == mailType) { mailclass.setCharset("UTF-8"); mailclass.setMsg(mailContent); } else { mailclass.setContent(mailBody); } // 增加需要回执的标记 mailclass.addHeader("Disposition-Notification-To", "1"); mailclass.send(); result = true; }catch(Exception e){ log.error("发件箱: " + this.mailFromAddress + "用户名: " + this.mailUser + "密码: " + this.mailPassword); throw new Exception(); } if (result) { System.out.println("已向下列邮箱发送了邮件"); if (mailTOAddress != null) { for (int i = 0; i < mailTOAddress.length; i++) { System.out.println(mailTOAddress[i]); } } if (mailCCAddress != null) { for (int i = 0; i < mailTOAddress.length; i++) { System.out.println(mailCCAddress[i]); } } if (mailBCCAddress != null) { for (int i = 0; i < mailTOAddress.length; i++) { System.out.println(mailBCCAddress[i]); } } } } /** * 邮件发送(不需要回执,且返回发送结果) * @return boolean 返回结果 * @throws MessagingException */ public boolean send() throws Exception { mailclass = new MultiPartEmail(); mailclass.setDebug(this.debug); if (mailTOAddress != null) { for (int i = 0; i < this.mailTOAddress.length; i++) { mailclass.addTo(mailTOAddress[i]); } } if (addChaoSong != null) { String[] mailAddr = addChaoSong.split(","); for (int i = 0; i < mailAddr.length; i++) { mailclass.addCc(mailAddr[i]); } } mailclass.setHostName(this.mailSMTPHost); mailclass.setSmtpPort(Integer.parseInt(this.mailSMTPHostPort)); //設置郵箱显示名 if(this.mailShowName != null ){ mailclass.setFrom(this.mailFromAddress, this.mailShowName); }else{ mailclass.setFrom(this.mailFromAddress, this.mailUser); } // mailclass.setAuthentication(this.mailUser, this.mailPassword); mailclass.setSubject(this.mailSubject); if (SIMPLE_MAIL == mailType) { mailclass.setCharset("UTF-8"); mailclass.setMsg(mailContent); } else { mailclass.setContent(mailBody); } // 不需要回执的标记 mailclass.send(); result = true; return result; } public String getMailContent() { return mailContent; } public void setMailContent(String mailContent) { this.mailContent = mailContent; } public Email getMailclass() { return mailclass; } public void setMailclass(MultiPartEmail mailclass) { this.mailclass = mailclass; } public int getMailType() { return mailType; } public void setMailType(int mailType) { this.mailType = mailType; } public String getMailShowName() { return mailShowName; } public void setMailShowName(String mailShowName) { this.mailShowName = mailShowName; } public String getAddChaoSong() { return addChaoSong; } public void setAddChaoSong(String addChaoSong) { this.addChaoSong = addChaoSong; } /**邮件发送通用方法 * @author sfit1092 * @param mailHost * @param fromMailAddr * @param fromMailUser * @param fromMailPwd * @param filePath * @param contentHTML * @param title * @param reciveAddress(多个联系人用","分隔) * @return */ /*public static boolean sentMail(String mailHost, String fromMailAddr, String fromMailUser, String fromMailPwd, String filePath, String contentHTML, String title, String reciveAddress) { try { MailCommon mail = new MailCommon(); mail.setAddress(reciveAddress.trim(), MailCommon.TO); mail.setFromAddress(fromMailAddr); mail.setSMTPHost(mailHost, null, fromMailUser, fromMailPwd); if (!"".equals(filePath)) { mail.setFileAttachment(filePath); } else { mail.setMailType(1); } mail.setSubject(new String(title.getBytes("UTF-8"), "UTF-8")); mail.setHtmlBody(contentHTML); mail.send(); return true; } catch (Exception e) { logger.error("邮件发送异常!"); return false; } }*/ public static boolean sentMail(String toAddress, String title, String htmlContent, String filePath) { ServletContext ctx = AppContext.getContext().getServletContext(); String mailHost = ctx.getAttribute("mail.host")==null?"":ctx.getAttribute("mail.host").toString(); String mailAddress = ctx.getAttribute("mail.address")==null?"":ctx.getAttribute("mail.address").toString(); // String mailUser = ctx.getAttribute("mail.user")==null?"":ctx.getAttribute("mail.user").toString(); // String mailPassword = ctx.getAttribute("mail.password")==null?"":ctx.getAttribute("mail.password").toString(); String mailUser = com.sf.novatar.context.AppContext.getContext().getConfigProperties().getProperty("mail.user"); String mailPassword = com.sf.novatar.context.AppContext.getContext().getConfigProperties().getProperty("mail.password"); MailCommon mail = new MailCommon(); mail.mailUser = mailUser; mail.mailPassword = mailPassword; try { mail.setAddress(toAddress.trim(), MailCommon.TO); mail.setFromAddress(mailAddress); mail.setSMTPHost(mailHost, null, mailUser, mailPassword); if (!"".equals(filePath)) { mail.setFileAttachment(filePath); } else { mail.setMailType(1); } mail.setSubject(new String(title.getBytes("UTF-8"), "UTF-8")); mail.setHtmlBody(htmlContent); mail.send(); return true; } catch (Exception e) { logger.error("邮件发送异常!"+e.getLocalizedMessage()); return false; } } }
使用apache commons组件发送邮件
猜你喜欢
转载自yaohongxing.iteye.com/blog/2276910
今日推荐
周排行