EmailHelper 工具类

来源:互联网 发布:算法设计与分析 以acm 编辑:程序博客网 时间:2024/06/04 04:14
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 Stringpassword = "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 "";
}
}
原创粉丝点击