EmailHelper 工具类

package org.platform.utils.email;


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;


import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


import org.platform.utils.md5.DESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public final class EmailHelper {
private final static Logger log = LoggerFactory.getLogger(EmailHelper.class);
String sender = "XXX@chinaexpressair.com";
String senderName = "XXX";
// 邮件的配置
// String smtp = "10.6.168.229";
String smtp  = "mail.chinaexpressair.com";
final String username = "zzjk2";
private final String password = "x5mXIzZ8Ix8rxWN7vQxfRQ==";

boolean isDebug = false; // 显示debug信息


private String port = "587";

private EmailHelper() {
}

public static EmailHelper init() {
return new EmailHelper();
}

/**
* 发送邮件

* @param subject
*            主题
* @param content
*            正文
* @param receivers
*            收件人
* @param attchs
*            附件
* @throws MessagingException
* @throws AddressException
* @throws UnsupportedEncodingException
*/
public void send(final String subject, final String content, final String receiver) throws MessagingException, AddressException, UnsupportedEncodingException {
// 收件人
final List<String> receivers = new ArrayList<String>();
receivers.add(receiver);
this.send(this.sender, this.senderName, subject, content, receivers, null, null, this.smtp, this.username, this.getPassword());
}

/**
* 发送邮件

* @param subject
*            主题
* @param content
*            正文
* @param receivers
*            收件人
* @param attchs
*            附件
* @throws MessagingException
* @throws AddressException
* @throws UnsupportedEncodingException
*/
public void send(final String subject, final String content, final String receiver, final String attch) throws MessagingException, AddressException, UnsupportedEncodingException {
// 收件人
final List<String> receivers = new ArrayList<String>();
receivers.add(receiver);
// 附件
final List<String> attchs = new ArrayList<String>();
if ((null != attch) && !"".equals(attch)) {
attchs.add(attch);
}

this.send(this.sender, this.senderName, subject, content, receivers, null, attchs, this.smtp, this.username, this.getPassword());
}

/**
* 发送邮件

* @param subject
*            主题
* @param content
*            正文
* @param receivers
*            收件人
* @param ccs
*            抄送人
* @param attchs
*            附件
* @throws MessagingException
* @throws AddressException
* @throws UnsupportedEncodingException
*/
public void send(final String subject, final String content, final List<String> receivers, final List<String> ccs, final List<String> attchs) throws MessagingException, AddressException,
UnsupportedEncodingException {
this.send(this.sender, this.senderName, subject, content, receivers, ccs, attchs, this.smtp, this.username, this.getPassword());
}

/**
* 发送邮件

* @param sender
*            发件人
* @param senderName
*            发件人的别名
* @param subject
*            主题
* @param content
*            正文
* @param receivers
*            收件人
* @param ccs
*            抄送人
* @param attchs
*            附件
* @param smtp
*            邮件服务器地址
* @param username
*            发件人账号
* @param password
*            发件人密码
* @throws MessagingException
* @throws AddressException
* @throws UnsupportedEncodingException
*/
public void send(final String sender, final String senderName, final String subject, final String content, final List<String> receivers, final List<String> ccs, final List<String> attchs,
final String smtp, final String username, final String password) throws MessagingException, AddressException, UnsupportedEncodingException {
/**
* 创建会话,Properties设置会话参数 将权限验证信息添加在session中
*/
final Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");// 需要权限认证
props.setProperty("mail.transport.protocol", "smtp");// 传输协议为smtp
props.setProperty("mail.host", smtp);// smtp的地址
props.setProperty("mail.smtp.port", port);// 端口
final Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(this.isDebug);// 调试信息

/**
* 创建邮件
*/
final Message msg = new MimeMessage(session);// 邮件需要和会话session绑定
msg.setFrom(new InternetAddress("\"" + MimeUtility.encodeText(senderName) + "\" <" + sender + ">"));// 发件人

// 添加收件人
msg.setRecipients(RecipientType.TO, InternetAddress.parse(this.getReceivers(receivers)));
// 添加抄送人
if ((null != ccs) && (ccs.size() > 0)) {
msg.setRecipients(RecipientType.CC, InternetAddress.parse(this.getReceivers(ccs)));
}
// 添加主题
msg.setSubject(subject);

// 添加邮件内容
msg.setContent(this.createContent(content, attchs));

// 保存邮件
msg.saveChanges();

/**
* 直接调用静态方法发送邮件 会自动创建和关闭连接
*/
Transport.send(msg);
}

/**
* 创建邮件内容,包括正文和附件

* @param content
*            正文
* @param attchs
*            附件
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
private MimeMultipart createContent(final String content, final List<String> attchs) throws MessagingException, UnsupportedEncodingException {

final MimeMultipart msgMultipart = new MimeMultipart("mixed");// 定义结构体,类型为复合类型
// 添加正文
msgMultipart.addBodyPart(this.createContentPart(content));// 添加正文
// 添加附件
if ((null != attchs) && (attchs.size() > 0)) {
for (final String path : attchs) {
msgMultipart.addBodyPart(this.createAttchPart(path));
}
}

return msgMultipart;
}

/**
* 解析收件人

* @param receivers
* @return
*/
private String getReceivers(final List<String> receivers) {
final StringBuffer recStr = new StringBuffer();
for (final String r : receivers) {
recStr.append(r).append(',');
}
return recStr.toString();
}

/**
* 创建正文

* @param content
* @return
* @throws MessagingException
*/
private MimeBodyPart createContentPart(final String content) throws MessagingException {
final MimeBodyPart contentPart = new MimeBodyPart();// 正文部分
contentPart.setContent(content, "text/html;charset=gbk");
return contentPart;
}

/**
* 创建附件

* @param attchPath
*            附件文件的路径"e:/1.png";
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
private MimeBodyPart createAttchPart(final String attchPath) throws MessagingException, UnsupportedEncodingException {
final MimeBodyPart attch = new MimeBodyPart();
final DataSource ds1 = new FileDataSource(attchPath);
final DataHandler dh1 = new DataHandler(ds1);
attch.setDataHandler(dh1);
attch.setFileName(MimeUtility.encodeText(attchPath.substring(attchPath.lastIndexOf('/'))));
return attch;
}

public void send(final String subject, final String content, final Map<String, String> receivers, final Map<String, String> ccs) throws MessagingException, AddressException,
UnsupportedEncodingException {
/**
* 创建会话,Properties设置会话参数 将权限验证信息添加在session中
*/
final Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");// 需要权限认证
props.setProperty("mail.transport.protocol", "smtp");// 传输协议为smtp
props.setProperty("mail.host", this.smtp);// smtp的地址
props.setProperty("mail.smtp.port", port);// 端口
final Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(EmailHelper.this.username, EmailHelper.this.getPassword());
}
});
session.setDebug(this.isDebug);// 调试信息

/**
* 创建邮件
*/
final Message msg = new MimeMessage(session);// 邮件需要和会话session绑定
msg.setFrom(new InternetAddress("\"" + MimeUtility.encodeText(this.senderName) + "\" <" + this.sender + ">"));// 发件人

// 添加收件人
msg.setRecipients(RecipientType.TO, InternetAddress.parse(this.getReceivers(receivers)));
// 添加抄送人
if ((null != ccs) && (ccs.size() > 0)) {
msg.setRecipients(RecipientType.CC, InternetAddress.parse(this.getReceivers(ccs)));
}
// 添加主题
msg.setSubject(subject);

// 添加邮件内容
msg.setText(content);

// 保存邮件
msg.saveChanges();

/**
* 直接调用静态方法发送邮件 会自动创建和关闭连接
*/
Transport.send(msg);
}

public void sendHtml(final String subject, final String content, final Map<String, String> receivers, final Map<String, String> ccs) throws MessagingException, AddressException,
UnsupportedEncodingException {
/**
* 创建会话,Properties设置会话参数 将权限验证信息添加在session中
*/
final Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");// 需要权限认证
props.setProperty("mail.transport.protocol", "smtp");// 传输协议为smtp
props.setProperty("mail.host", this.smtp);// smtp的地址
props.setProperty("mail.smtp.port", port);// 端口
final Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(EmailHelper.this.username, EmailHelper.this.getPassword());
}
});
session.setDebug(this.isDebug);// 调试信息

/**
* 创建邮件
*/
final Message msg = new MimeMessage(session);// 邮件需要和会话session绑定
msg.setFrom(new InternetAddress("\"" + MimeUtility.encodeText(this.senderName) + "\" <" + this.sender + ">"));// 发件人

// 添加收件人
msg.setRecipients(RecipientType.TO, InternetAddress.parse(this.getReceivers(receivers)));
// 添加抄送人
if ((null != ccs) && (ccs.size() > 0)) {
msg.setRecipients(RecipientType.CC, InternetAddress.parse(this.getReceivers(ccs)));
}
// 添加主题
msg.setSubject(subject);

// 添加邮件内容
msg.setContent(this.createContent(content, null));
// 保存邮件
msg.saveChanges();

/**
* 直接调用静态方法发送邮件 会自动创建和关闭连接
*/
Transport.send(msg);

}



private String getReceivers(final Map<String, String> receivers) {
final StringBuffer recStr = new StringBuffer();
if ((null != receivers) && (receivers.size() > 0)) {
for (final Object element : receivers.keySet()) {
final String userName = (String) element;
final String userAlias = receivers.get(userName);
String temp = "";
try {
temp = "\"" + MimeUtility.encodeText(userAlias) + "\" <" + userName + ">";
} catch (final UnsupportedEncodingException e) {
log.error("EmailHelper操作错误:",e);
}
recStr.append(temp).append(',');
}
}
return recStr.toString();
}


public String getPassword() {
try {
return DESUtil.decrypt(this.password);
} catch (Exception e) {
log.error("EmailHelper操作错误:",e);
}
return "";
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值