package com.hp.poc.common;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmailsSend {
//BCC一次100个用户
final int BCC_SIZE = 100;
//每隔10秒发送一次
final int PEROID = 100000;
final Logger Log = LoggerFactory.getLogger(EmailsSend.class);
ArrayList<String> partsList=new ArrayList<String>();
String subject="",body="";
public EmailsSend() {
super();
}
public EmailsSend(ArrayList<String> partsList, String subject, String body) {
super();
this.partsList = partsList;
this.subject = subject;
this.body = body;
}
public ArrayList<String> setps(String subject,String body,ArrayList<String> to) throws Exception{
ArrayList<String> smallArray=null;
ArrayList<String> errArray=new ArrayList<String>();
double c=(double)to.size()/(double)BCC_SIZE;
int k=((Double)Math.ceil(c)).intValue();
int i=0;
for(int j=1;j<=k;j++){
smallArray=new ArrayList<String>();
for(;i<j*BCC_SIZE&&i<to.size();i++){
smallArray.add(to.get(i));
}
boolean emailState=this.setp(subject, body, smallArray);
if(emailState){
Thread.sleep(PEROID);
}else{
Thread.sleep(3*PEROID);
emailState=this.setp(subject, body, smallArray);
if(!emailState){
errArray.addAll(smallArray);
}
}
}
return errArray;
}
private boolean setp(String subject,String body,ArrayList<String> to) throws Exception{
HashMap<String, String> map=sendEmailByCustomerMailServer(subject,body,to,null);
if(map.get("state").toString().equals("success")){
return true;
}
return false;
}
private HashMap<String, String> sendEmailByCustomerMailServer(String subject,
String body, ArrayList<String> to, ArrayList<String> cc) {
HashMap<String, String> map = new HashMap<String, String>();
String message = "邮件发送成功!";
map.put("state", "success");
map.put("message", message);
try {
Properties props = new Properties();
props.put("mail.smtp.host",
ChannelConfig.getValue("mail.smtp.host"));
String port = ChannelConfig.getValue("mail.smtp.port");
String auth = ChannelConfig.getValue("mail.smtp.auth");
String from=ChannelConfig.getValue("mail.smtp.username");
if (auth != null && !"".equals(auth.trim()) && "true".equals(auth)) {
props.put("mail.smtp.auth", auth);
if (port != null && !"".equals(port.trim())) {
props.put("mail.smtp.port", port);
}
} else {
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.timeout", "0");
}
// Getting the Mail Session Object
Session mailConnection = Session.getDefaultInstance(props);
Transport transport = mailConnection.getTransport("smtp");
if (auth != null && !"".equals(auth.trim()) && "true".equals(auth)) {
transport.connect(ChannelConfig.getValue("mail.smtp.host"),
ChannelConfig.getValue("mail.smtp.username"),
ChannelConfig.getValue("mail.smtp.password"));
} else {
transport.connect();
}
Message msg = new MimeMessage(mailConnection);
msg = buildMessage(msg, subject, body, from, to, cc);
transport.sendMessage(msg, msg.getAllRecipients());
org.jfree.util.Log.info(message+" "+to.toString());
return map;
} catch (Exception e) {
message="邮件发送失败!错误原因:\n"+e.getMessage();
map.put("state", "failed");
map.put("message", message);
e.printStackTrace();
org.jfree.util.Log.error(message+" "+to.toString());
}
return map;
}
private Message buildMessage(Message msg, String subject,
String body, String from, ArrayList<String> to, ArrayList<String> cc) throws UnsupportedEncodingException, MessagingException{
Address[] toAdd = buildEmaiAddress(to);
Address fromAdd = new InternetAddress(from);
msg.setFrom(fromAdd);
msg.setRecipients(Message.RecipientType.BCC, toAdd);
if (cc != null && cc.size() > 0) {
Address[] ccAdd = buildEmaiAddress(cc);
msg.setRecipients(Message.RecipientType.CC, ccAdd);
}
msg.setSubject(MimeUtility.encodeText(subject,
MimeUtility.mimeCharset("UTF-8"), null));
msg.setContent(body, "text/html;charset=utf-8");
return msg;
}
private Address[] buildEmaiAddress(ArrayList<String> addressArray) throws AddressException{
if(addressArray == null || addressArray.size() == 0) {
return null;
}
Address[] addressList = new Address[addressArray.size()];
for (int i = 0; i < addressArray.size(); i++){
addressList[i] = new InternetAddress(addressArray.get(i));
}
return addressList;
}
}
@GET
@Path("setp")
@Produces(MediaType.TEXT_PLAIN)
public String sendEmailsToAllPartner() throws Exception{
String sql="SELECT DISTINCT authorities.`UserName` FROM authorities,users WHERE " +
"authorities.`UserName`=users.`UserName` AND authorities.`authority`='ROLE_PARTNER' " +
"AND users.`CompanyID` IS NOT NULL AND LENGTH(authorities.`UserName`)>3 ORDER BY authorities.`UserName`;";
ArrayList<String> partsList=(ArrayList<String>) dao.findByNativeSql(sql.toString());
File currPathFile=new File(Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath());
File attFile=new File(currPathFile.getParentFile().getParentFile().getPath() + File.separator + "template"+File.separator+"html_tw.html");
String body=EmailHelper.loadPage(attFile);
String subject="管理平台 即日起正式啟用";
partsList=new ArrayList<String>();
// for(int i=0;i<1133;i++){
// partsList.add("wen@pp.com");
// }
EmailsSend es=new EmailsSend();
String errAddr=es.setps(subject, body, partsList).toString();
Log.info(errAddr);
return errAddr;
}