package com.test.util;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
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 javax.mail.util.ByteArrayDataSource;
import org.apache.log4j.Logger;
import com.test.exception.ErrorMessageException;
import com.test.exception.MessageRuntimeException;
public class SendMail extends Thread {
private final Logger log = Logger.getLogger(SendMail.class);
private String to = ""; // 收件人
private String from = ""; // 发件人
private String host = ""; // smtp主机
private String username = "";
private String password = "";
private String filename = ""; // 附件文件名
private String subject = ""; // 邮件主题
private String content = ""; // 邮件正文
private Vector file = new Vector(); // 附件文件集合
/**
* <br/>
* 方法说明:默认构造器 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public SendMail() {}
/**
* <br/>
* 方法说明:构造器,提供直接的参数传入 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public SendMail(String to, String from, String smtpServer, String username, String password, String subject, String content) {
this.to = to;
this.from = from;
this.host = smtpServer;
this.username = username;
this.password = password;
this.subject = subject;
this.content = content;
}
/**
* <br/>
* 方法说明:设置邮件服务器地址 <br/>
* 输入参数:String host 邮件服务器地址名称 <br/>
* 返回类型:
*/
public void setHost(String host) {
this.host = host;
}
/**
* <br/>
* 方法说明:设置登录服务器校验密码 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public void setPassWord(String pwd) {
this.password = pwd;
}
/**
* <br/>
* 方法说明:设置登录服务器校验用户 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public void setUserName(String usn) {
this.username = usn;
}
/**
* <br/>
* 方法说明:设置邮件发送目的邮箱 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public void setTo(String to) {
this.to = to;
}
/**
* <br/>
* 方法说明:设置邮件发送源邮箱 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public void setFrom(String from) {
this.from = from;
}
/**
* <br/>
* 方法说明:设置邮件主题 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
* <br/>
* 方法说明:设置邮件内容 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public void setContent(String content) {
this.content = content;
}
/**
* <br/>
* 方法说明:把主题转换为中文 <br/>
* 输入参数:String strText <br/>
* 返回类型:
*/
public String transferChinese(String strText) {
try {
strText = MimeUtility.encodeText(new String(strText.getBytes(), "GB2312"), "GB2312", "B");
}catch(Exception e) {
e.printStackTrace();
}
return strText;
}
/**
* <br/>
* 方法说明:往附件组合中添加附件 <br/>
* 输入参数: <br/>
* 返回类型:
*/
public void attachfile(String fname) {
file.addElement(fname);
}
/**
* <br/>
* 方法说明:发送邮件 <br/>
* 输入参数: <br/>
* 返回类型:boolean 成功为true,反之为false
*
* @throws IOException
*/
public void run() {
// 构造mail session
Properties props = System.getProperties();
if(host == null) {
throw new MessageRuntimeException("没有设置邮件发送服务器");
}
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 构造MimeMessage 并设定基本的值
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
subject = transferChinese(subject);
msg.setSubject(subject);
// 构造Multipart
Multipart mp = new MimeMultipart();
// 向Multipart添加正文
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setText(content);
// 向MimeMessage添加(Multipart代表正文)
mp.addBodyPart(mbpContent);
// 向Multipart添加附件
/*
* Enumeration efile = file.elements(); while (efile.hasMoreElements()) { MimeBodyPart mbpFile = new MimeBodyPart(); filename =
* efile.nextElement().toString(); FileDataSource fds = new FileDataSource(filename); mbpFile.setDataHandler(new
* DataHandler(fds)); mbpFile.setFileName(fds.getName()); //向MimeMessage添加(Multipart代表附件) mp.addBodyPart(mbpFile); }
* file.removeAllElements();
*/
// 向Multipart添加MimeMessage
msg.setContent(mp);
msg.setSentDate(new Date());
// 发送HTML
collect(msg);
// 发送邮件
Transport.send(msg);
} catch(AuthenticationFailedException e) {
log.error(e.getMessage(), e);
throw new MessageRuntimeException("邮箱认证失败,请检查您的账号和密码是否正确,并且确认已经开启了pop3/smtp邮箱服务", e);
} catch(SendFailedException e) {
log.error(e.getMessage(), e);
throw new MessageRuntimeException("邮箱认证失败,请检查您的账号和密码是否正确,并且确认已经开启了pop3/smtp邮箱服务", e);
}catch(Exception mex) {
log.error(mex.getMessage(), mex);
throw new ErrorMessageException("系统邮件发送失败!",mex);
}
}
public void collect(Message msg) throws MessagingException, IOException {
String subject = msg.getSubject();
StringBuffer sb = new StringBuffer();
sb.append("<HTML>\n");
sb.append("<HEAD>\n");
sb.append("<TITLE>\n");
sb.append(subject + "\n");
sb.append("</TITLE>\n");
sb.append("</HEAD>\n");
sb.append("<BODY>\n");
sb.append(this.content + "\n\n");
sb.append("</BODY>\n");
sb.append("</HTML>\n");
msg.setDataHandler(new DataHandler(new ByteArrayDataSource(sb.toString(), "text/html")));
}
/**
* 发送文本邮件
* @throws IOException
*/
public void sendMail() {
SendMail sendEmail = new SendMail();
sendEmail.setHost("smtp.163.com");
sendEmail.setUserName("test");
sendEmail.setPassWord("test");
sendEmail.setFrom("test@163.com");
sendEmail.setTo("test1@163.com");
sendEmail.setSubject("test");
sendEmail.setContent("test");
sendEmail.run();
}
}