public class Mail {
private final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
private String host = null; //服务器
private int port = 25; //端口
private String auth = null; //权限
private String username = null; //用户邮箱
private String password = null; //密码
private boolean mailusername = false; //是否显示个人名称
private Session session = null; //会话
/**
* 线程池
*/
ThreadPoolExecutor executor = null;{
executor = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
}
/**
* 此方法描述的是:初始化邮件服务
* @param mails
*/
@SuppressWarnings("unchecked")
public Mail(Map<String,String> mails) {
this.host = mails.get("server"); //服务器
int tempPort = Common.toDigit(mails.get("port")); //端口
if(tempPort > 0){
this.port = tempPort;
}
this.auth = mails.get("auth"); //权限
this.username=mails.get("auth_username"); //权限名
this.password=mails.get("auth_password"); //权限密码
if("1".equals(mails.get("mailusername"))){
this.mailusername = true;
}
}
/**
* 此方法描述的是:初始化邮件服务
* @param host 服务器
* @param port 端口
* @param auth 权限
* @param username 用户名
* @param password 密码
* @param mailusername 是否显示个人名称
*/
public Mail(String host, int port, String auth, String username, String password, String mailusername) {
this.host = host;
if(port > 0){
this.port=port;
}
this.auth = auth;
this.username = username;
this.password = password;
if("1".equals(mailusername)){
this.mailusername = true;
}
}
/**
* 此方法描述的是:创建会话
*/
private synchronized void createSession() {
Properties mailProps = new Properties();
mailProps.setProperty("mail.transport.protocol", "smtp"); //协议
mailProps.setProperty("mail.smtp.host", host); //主机
mailProps.setProperty("mail.smtp.port", String.valueOf(port)); //端口
if("smtp.gmail.com".equals(host)){
mailProps.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
mailProps.setProperty("mail.smtp.socketFactory.fallback", "false");
mailProps.setProperty("mail.smtp.socketFactory.port",String.valueOf(port));
}
if ("1".equals(auth)) { //权限
mailProps.put("mail.smtp.auth", "true");
}
//--默认初始化
session = Session.getDefaultInstance(mailProps, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
/**
* 此方法描述的是:创建 MimeMessage
* @return
*/
private MimeMessage createMimeMessage() {
if (session == null) {
createSession();
}
return new MimeMessage(session);
}
/**
* 此方法描述的是:发送邮件
* @param from 发送邮件
* @param toEmail 目标邮件
* @param subject 标题
* @param textBody 内容
* @param htmlBody html
* @return
*/
public String sendMessage(String from, String toEmail, String subject, String textBody, String htmlBody) {
String result = null;
try {
String encoding = MimeUtility.mimeCharset(JspRunConfig.CHARSET); //编码
MimeMessage message = createMimeMessage(); //创建信息
String toEmails[] = toEmail.split(","); //目标邮件组
Address to[] = new Address[toEmails.length]; //地址长度
for (int i = 0; i<toEmails.length; i++) {
String sTo = toEmails[i];
if(sTo.matches("^.*<.*>$")){
int index = sTo.indexOf("<");
to[i] = new InternetAddress(sTo.substring(index+1,sTo.length()-1), mailusername?sTo.substring(0, index):"", encoding);
}else{
to[i] = new InternetAddress(sTo, "", encoding);
}
}
String fromName = null;
String fromEmail;
if(from.matches("^.*<.*>$")){
int index = from.indexOf("<");
if(mailusername){
fromName = from.substring(0, index);
}
fromEmail = from.substring(index+1,from.length()-1);
}else{
fromEmail = from;
}
Address fromAddress = new InternetAddress(fromEmail,fromName!=null?fromName:"", encoding);
message.setHeader("Date", Common.gmdate("EEE, dd MMM yyyy HH:mm:ss Z", (int)(System.currentTimeMillis()/1000), "0"));
message.setHeader("Content-Transfer-Encoding", "8bit");
message.setRecipients(Message.RecipientType.TO, to);
message.setFrom(fromAddress);
message.setSubject(subject, encoding);
MimeMultipart content = new MimeMultipart("alternative");
if (textBody != null && htmlBody != null) {
MimeBodyPart text = new MimeBodyPart();
text.setText(textBody, encoding);
text.setDisposition(Part.INLINE);
content.addBodyPart(text);
MimeBodyPart html = new MimeBodyPart();
html.setContent(htmlBody, "text/html; charset="+encoding);
html.setDisposition(Part.INLINE);
content.addBodyPart(html);
} else if (textBody != null) {
MimeBodyPart text = new MimeBodyPart();
text.setText(textBody, encoding);
text.setDisposition(Part.INLINE);
content.addBodyPart(text);
} else if (htmlBody != null) {
MimeBodyPart html = new MimeBodyPart();
html.setContent(htmlBody, "text/html; charset="+encoding);
html.setDisposition(Part.INLINE);
content.addBodyPart(html);
}
message.setContent(content);
message.setDisposition(Part.INLINE);
addToTask(message);
} catch (Exception e) {
result=e.getMessage();
}
return result;
}
/**
* 此方法描述的是:添加线程
* @param message
*/
private void addToTask(MimeMessage message) {
if (message != null) {
sendMessages(Collections.singletonList(message));
} else {
System.out.println("Cannot add null email message to queue.");
}
}
/**
* 此方法描述的是:发送邮件
* @param messages
*/
private void sendMessages(Collection<MimeMessage> messages) {
if (messages.size() == 0) {
return;
}
executor.execute(new EmailTask(messages));
}
/**
* 此文件描述的是:多线程邮件发送
* @author blaiu
*
*/
private class EmailTask implements Runnable {
private Collection<MimeMessage> messages;
public EmailTask(Collection<MimeMessage> messages) {
this.messages = messages;
}
public void run() {
try {
sendMessages();
} catch (MessagingException me) {
me.printStackTrace();
int timestamp =(int)(System.currentTimeMillis()/1000);
Log.writelog("errorlog", timestamp, timestamp+"\tSMTP\t\t("+host+":"+port+") CONNECT - Unable to connect to the SMTP server");
}
}
public boolean sendMessages() throws MessagingException {
Transport transport = null;
try {
URLName url = new URLName("smtp", host, port, "", username, password);
transport = new SMTPTransport(session, url);
transport.connect(host, port, username, password);
for (MimeMessage message : messages) {
transport.sendMessage(message, message.getRecipients(MimeMessage.RecipientType.TO));
}
return true;
} finally {
if (transport != null) {
transport.close();
}
}
}
}
}