package wfc.service.util;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
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.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import wfc.service.log.Log;
/**
* 邮件处理<br>
*
* <p>
* <b>使用示例</b>
* <p style="margin-left:35px">
* <code><b>
* <br>MailSender mailSender = new MailSender("mail-svr", "user", "pwd");
* <br>mailSender.setFromAddress("yuyue@wondersgroup.com");
* <br>mailSender.setSubject("测试邮件");
* <br>mailSender.addTOAddress("chenlin@wondersgroup.com");
* <br>mailSender.addCCAddress("yuyue@wondersgroup.com");
* <br>mailSender.addURLAttachment("http://www.sina.com.cn");
* <br>mailSender.addFileAttachment("c:\\autoexec.bat");
* <br>mailSender.send();
* </b></code>
*
*/
public class MailSender {
/** 邮件优先级, 最高级 */
public static String PRIORITY_HIGHEST = "1";
/** 邮件优先级, 高级 */
public static String PRIORITY_HIGH = "2";
/** 邮件优先级, 普通级 */
public static String PRIORITY_NORMAL = "3";
/** 邮件优先级, 低级 */
public static String PRIORITY_LOW = "4";
/** 邮件优先级, 最低级 */
public static String PRIORITY_LOWEST = "5";
/** 邮件发送对象 */
private MimeMessage mimeMessage;
/** 邮件相关信息 - 邮件正文(复合结构) */
private MimeMultipart mimeMultipart = new MimeMultipart("related");
/**
* 构造函数
*
* @param host
* 邮件SMTP服务器地址或名称
* @param port
* 邮件SMTP服务器端口号
* @param username
* 登录用户
* @param password
* 用户口令
*/
public MailSender(String host, int port, String username, String password)
throws MessagingException {
init(host, new Integer(port), username, password);
}
/**
* 构造函数, 默认SMTP服务器端口为25
*
* @param host
* 邮件SMTP服务器地址或名称
* @param username
* 登录用户
* @param password
* 用户口令
*/
public MailSender(String host, String username, String password)
throws MessagingException {
init(host, null, username, password);
}
/**
* 构造函数, 匿名发送需服务器支持
*
* @param host
* 邮件SMTP服务器地址或名称
* @param port
* 邮件SMTP服务器端口号
*/
public MailSender(String host, int port) throws MessagingException {
init(host, new Integer(port), null, null);
}
/**
* 构造函数, 默认SMTP服务器端口为25, 匿名发送需服务器支持
*
* @param host
* 邮件SMTP服务器地址或名称
*/
public MailSender(String host) throws MessagingException {
init(host, null, null, null);
}
private void init(String host, Integer port, String username,
String password) throws MessagingException {
Properties properties = System.getProperties();
properties.put("mail.smtp.host", host);
if (port != null) {
properties.put("mail.smtp.port", String.valueOf(port.intValue()));
}
Session session;
if (username != null) {
properties.put("mail.smtp.auth", "true");
Authenticator auth = new MailAuthenticator(username, password);
session = Session.getInstance(properties, auth);
} else {
session = Session.getInstance(properties);
}
mimeMessage = new MimeMessage(session);
mimeMessage.setSentDate(new Date());
mimeMessage.setContent(mimeMultipart);
}
/**
* 设置邮件发送地址
*
* @param address
* 邮件发送地址
*/
public void setFromAddress(String address) throws MessagingException {
mimeMessage.setFrom(new InternetAddress(address));
}
/**
* 设置邮件普通接收方地址
*
* @param address
* 邮件地址
* @throws MessagingException
*/
public void addTOAddress(String address) throws MessagingException {
mimeMessage.addRecipients(RecipientType.TO, address);
}
/**
* 设置邮件抄送接收方地址
*
* @param address
* 邮件地址
* @throws MessagingException
*/
public void addCCAddress(String address) throws MessagingException {
mimeMessage.addRecipients(RecipientType.CC, address);
}
/**
* 设置邮件密件抄送接收方地址
*
* @param address
* 邮件地址
* @throws MessagingException
*/
public void addBCCAddress(String address) throws MessagingException {
mimeMessage.addRecipients(RecipientType.BCC, address);
}
/**
* 设置邮件回复地址
*
* @param address
* 邮件回复地址
*/
public void setReplyAddress(String address) throws MessagingException {
Address[] addresses = { new InternetAddress(address) };
mimeMessage.setReplyTo(addresses);
}
/**
* 设置邮件主题
*
* @param subject
* 邮件主题
*/
public void setSubject(String subject) throws MessagingException {
mimeMessage.setSubject(subject);
}
/**
* 设置邮件优先级
*
* @param priority
* 优先级, 见常量定义
* @throws MessagingException
*/
public void setPriority(String priority) throws MessagingException {
mimeMessage.addHeader("X-Priority", priority);
}
/**
* 设置邮件文本正文
*
* @param textBody
* 邮件文本正文
* @throws MessagingException
*/
public void addTextBody(String textBody) throws MessagingException {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setText(textBody, "GBK");
mimeMultipart.addBodyPart(mimeBodyPart);
}
/**
* 设置邮件超文本正文
*
* @param htmlBody
* 邮件超文本正文
* @throws MessagingException
*/
public void addHtmlBody(String htmlBody) throws MessagingException {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(htmlBody,
"text/html;charset=GBK"));
mimeMultipart.addBodyPart(mimeBodyPart);
}
/**
* 设置邮件正文外部链接 URL, 信体中将包含链接所指向的内容
*
* @param urlAttachment
* 邮件正文外部链接 URL
* @throws MessagingException
* @throws MalformedURLException
*/
public void addURLAttachment(String urlAttachment)
throws MessagingException, MalformedURLException {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(new URL(urlAttachment)));
mimeMultipart.addBodyPart(mimeBodyPart);
}
/**
* 设置邮件正文外部链接 URL, 信体中将包含链接所指向的内容(包括链接所引用的图片文件)
*
* @param urlEmbeddedAttachment
* 邮件正文外部链接 URL
* @throws MessagingException
* @throws MalformedURLException
* @throws ParserException
* @throws IOException
*/
public void addURLEmbeddedAttachment(String urlEmbeddedAttachment)
throws MessagingException, MalformedURLException, ParserException,
IOException {
URL url = new URL(urlEmbeddedAttachment);
URLConnection con = url.openConnection();
Parser parser = new Parser(con);
parser.setEncoding("GBK");
NodeList htmlNodeList = new NodeList();
NodeList linkNodeList = new NodeList();
NodeList imageNodeList = new NodeList();
NodeList backgroundNodeList = new NodeList();
NodeIterator ni = parser.elements();
while (ni.hasMoreNodes()) {
Node node = ni.nextNode();
node.collectInto(linkNodeList, new TagNameFilter("LINK"));
node.collectInto(imageNodeList, new TagNameFilter("IMG"));
node.collectInto(htmlNodeList, new TagNameFilter("HTML"));
node.collectInto(backgroundNodeList, new HasAttributeFilter(
"BACKGROUND"));
}
for (int i = 0; i < linkNodeList.size(); i++) {
Tag tag = (Tag) linkNodeList.elementAt(i);
String linkUrl = tag.getPage().getAbsoluteURL(
tag.getAttribute("href"));
tag.setAttribute("href", "cid:LNK" + i);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(new URL(linkUrl)));
mimeBodyPart.setHeader("Content-ID", "LNK" + i);
mimeMultipart.addBodyPart(mimeBodyPart);
}
for (int i = 0; i < imageNodeList.size(); i++) {
ImageTag tag = (ImageTag) imageNodeList.elementAt(i);
String imageUrl = tag.getImageURL();
tag.setImageURL("cid:IMG" + i);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(new URL(imageUrl)));
mimeBodyPart.setHeader("Content-ID", "IMG" + i);
mimeMultipart.addBodyPart(mimeBodyPart);
}
for (int i = 0; i < backgroundNodeList.size(); i++) {
Tag tag = (Tag) backgroundNodeList.elementAt(i);
String imageUrl = tag.getPage().getAbsoluteURL(
tag.getAttribute("background"));
tag.setAttribute("background", "cid:BGIMG" + i);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(new URL(imageUrl)));
mimeBodyPart.setHeader("Content-ID", "BGIMG" + i);
mimeMultipart.addBodyPart(mimeBodyPart);
}
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(htmlNodeList.elementAt(0)
.toHtml(), "text/html;charset=GBK"));
mimeMultipart.addBodyPart(mimeBodyPart);
}
/**
* 设置邮件附件
*
* @param fileAttachment
* 文件的全路径
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void addFileAttachment(String fileAttachment)
throws MessagingException, UnsupportedEncodingException {
File file = new File(fileAttachment);
if (!file.exists() || file.isDirectory()) {
return;
}
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(new FileDataSource(
fileAttachment)));
// modified by zord @ 2003/6/16 to support Chinese File Name
mimeBodyPart.setFileName(MimeUtility.encodeText(file.getName()));
mimeMultipart.addBodyPart(mimeBodyPart);
}
/**
* 邮件发送(一次发送多个地址, 优点速度快, 但是有非法邮件地址时将中断发送操作)
*
* @throws MessagingException
*/
public void sendBatch() throws MessagingException {
Transport.send(mimeMessage);
Address[] addresses = mimeMessage.getAllRecipients();
for (int i = 0; i < addresses.length; i++) {
Log.debug(addresses[i] + " 发送成功");
}
}
/**
* 邮件发送(一个地址一个地址地发送, 优点是有非法邮件地址时不会中断发送操作, 缺点速度慢)
*
* @throws MessagingException
*/
public void send() throws MessagingException {
Address[] addresses = mimeMessage.getAllRecipients();
for (int i = 0; i < addresses.length; i++) {
try {
Transport.send(mimeMessage, new Address[] { addresses[i] });
Log.debug(addresses[i] + " 发送成功");
} catch (MessagingException e) {
Log.error(e);
Log.debug(addresses[i] + " 发送失败");
}
}
}
private static class MailAuthenticator extends Authenticator {
private String user;
private String pass;
public MailAuthenticator(String user, String pass) {
this.user = user;
this.pass = pass;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
}
}