package com.tmg.aec.common.until;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;
/**
* @author duanzc
* @date:2010-10-19 下午02:30:30
* @version :1.0
* @类说明:发送邮件,线程安全
*/
public class EmailSenderByThread extends MyThread{
private static final String charset = "UTF-8";
private static final String defaultMimetype = "text/plain";
private static final String nickname = "看图说话";
private static final String PORT = "25";
private static final String SMTP = "ma.sai.ke";
private static final String myEmailAddress = "ma.sai.ke";
private static final String myEmailPWD = "ma.sai.ke";
private static final String isVerification = "true";
public static void main(String[] args) {
String[] mails = new String[] {"635343934@qq.com",
"duanzuocai@yahoo.com.cn", "duanzuocai@sohu.com",
"duanzuocai@foxmail.com", "duanzuocai@gmail.com",
"duanzuocai@hotmail.com", "duanzuocai@163.com",
"duanzuocai@126.com","duanzuocai@sina.com"};
String cont = "月圆之夜,紫荆之巅。一剑西来,天外飞仙。";
try {
for(String s:mails)
EmailSenderByThread.send(s, "看图说话", cont, "text/html");
} catch (Exception e) {
e.printStackTrace();
}
}
// ======================= 初始化线程 =============================
// 参数
String[] receivers;
File[] attachements;
String subject, mailContent, mimetype;
/** 最多同时执行的任务数 */
private static ExecutorService service = Executors.newFixedThreadPool(MyThread.getMaxThread());
private static List<MyThread> threads = new ArrayList();
static{
for(int i = 0; i < MyThread.getMaxThread() + 1; i++){
threads.add(new EmailSenderByThread());
}
}
// ======================= 初始化线程 =============================
@Override
public void runCode() throws MessagingException, UnsupportedEncodingException {
Properties props = new Properties();
props.put("mail.smtp.port", PORT); // 端口
props.put("mail.smtp.host", SMTP); // smtp服务器地址
props.put("mail.smtp.auth", isVerification); // 需要校验
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myEmailAddress,
myEmailPWD); // 登录用户名/密码
}
});
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
InternetAddress sender = new InternetAddress(myEmailAddress);
sender.setPersonal(nickname, charset); // 昵称(UTF-8编码)
mimeMessage.setFrom(sender); // 发件人邮件
InternetAddress[] toAddress = new InternetAddress[receivers.length];
for (int i = 0; i < receivers.length; i++) {
toAddress[i] = new InternetAddress(receivers[i]);
}
mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);// 收件人邮件
mimeMessage.setSubject(subject, charset);
Multipart multipart = new MimeMultipart();
// 正文
MimeBodyPart body = new MimeBodyPart();
// body.setText(mailContent, charset);//不支持html
body.setContent(mailContent,
(mimetype != null && !"".equals(mimetype) ? mimetype
: defaultMimetype)
+ ";charset=" + charset);
multipart.addBodyPart(body);// 发件内容
// 附件
if (attachements != null) {
for (File attachement : attachements) {
MimeBodyPart attache = new MimeBodyPart();
attache.setDataHandler(new DataHandler(new FileDataSource(
attachement)));
String fileName = getLastName(attachement.getName());
attache.setFileName(MimeUtility.encodeText(fileName, charset,
null));
multipart.addBodyPart(attache);
}
}
mimeMessage.setContent(multipart);
mimeMessage.setSentDate(new Date());
Transport.send(mimeMessage);
}
@Override
public void setArgs(Object... args) {
this.receivers = (String[]) args[0];
this.subject = args[1].toString();
this.mailContent = args[2].toString();
this.attachements = (File[]) args[3];
this.mimetype = args[4].toString();
}
/**
* 发送邮件
*
* @param receivers 收件人
* @param subject 标题
* @param mailContent 邮件内容
* @param attachements 附件
* @param mimetype 内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public static void send(String[] receivers, String subject,
String mailContent, File[] attachements, String mimetype)
throws MessagingException, UnsupportedEncodingException {
MyThread m = MyThread.getMyThread(threads, receivers, subject,
mailContent, attachements, mimetype);
service.execute(m);
}
/**
* 发送邮件
*
* @param receiver 收件人
* @param subject 标题
* @param mailContent 邮件内容
* @param mimetype 内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public static void send(String receiver, String subject,
String mailContent, String mimetype)
throws UnsupportedEncodingException, MessagingException {
send(new String[] { receiver }, subject, mailContent, mimetype);
}
/**
* 发送邮件
*
* @param receivers 收件人
* @param subject 标题
* @param mailContent 邮件内容
* @param mimetype 内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public static void send(String[] receivers, String subject,
String mailContent, String mimetype)
throws UnsupportedEncodingException, MessagingException {
send(receivers, subject, mailContent, null, mimetype);
}
private static String getLastName(String fileName) {
int pos = fileName.lastIndexOf("\\");
if (pos > -1) {
fileName = fileName.substring(pos + 1);
}
pos = fileName.lastIndexOf("/");
if (pos > -1) {
fileName = fileName.substring(pos + 1);
}
return fileName;
}
}
线程类:
package com.tmg.aec.common.until;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author duanzc
* @date:2010-10-18 上午10:27:21
* @version :1.0
* @类说明:线程池
*/
@SuppressWarnings("unchecked")
public abstract class MyThread implements Runnable {
/** 线程出错后重新运行次数 */
private static int errorTimes = 2;
/** 最多同时执行任务数 */
private static int maxThread = 2;
/** 线程使用状态:false未使用、true使用中 */
private String thread_states = "false";
/**
* 得到空闲线程、并传递参数
* @param threads 线程池
* @param args 参数
* @return
*/
protected static MyThread getMyThread(List<MyThread> threads, Object ... args) {
for(MyThread t:threads){
if(t.thread_states.equals("false")){
t.thread_states = "true"; // 标记使用中
t.setArgs(args);
return t;
}
}
try {
Thread.sleep(1500L);
} catch (Exception e) {
e.printStackTrace();
}
return getMyThread(threads, args);
}
public void close(){
this.thread_states = "false";
}
/** 执行代码 */
public abstract void runCode() throws Exception;
/** 设置参数 */
public abstract void setArgs(Object ... args);;
/** 异常获取、重新执行代码 */
public void run() {
try {
runCode();
this.close();
} catch (Exception e) {
e.printStackTrace();
if(getErrorTimes()>0){
setErrorTimes(getErrorTimes() - 1);
run();
}
this.close();
}
}
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(2);
List<MyThread> list = new ArrayList();
// list.add(new MyThread());
for(int i = 0; i < 1; i++){
MyThread m = getMyThread(list, i+"",i+""+i);
service.submit(m);
m.close();
}
}
// --------------------------------------
public int getErrorTimes() {
return errorTimes;
}
public void setErrorTimes(int errorTimes) {
this.errorTimes = errorTimes;
}
public static int getMaxThread() {
return maxThread;
}
public static void setMaxThread(int maxThread) {
MyThread.maxThread = maxThread;
}
public String getThread_states() {
return thread_states;
}
public void setThread_states(String threadStates) {
thread_states = threadStates;
}
}