package com.icicle.framework.member.server.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileTypeMap;
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;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.icicle.framework.member.client.SendingEmailEnvelope;
import com.icicle.framework.member.client.SendingEmailEnvelope.Attachment;
public class SendingEmailUtilImpl implements SendingEmailUtil{
private static final Logger logger = Logger.getLogger(SendingEmailUtilImpl.class);
private String host;
private String emailUser;
private String displayUserName;
private String password;
private String port;
protected String switcher;
private MessageTemplate emailSubjectTemplate;
private MessageTemplate emailContentTemplate;
@Override
public void sendEmail(SendingEmailEnvelope envelope)
throws MessagingException {
logger.debug("Sending Subject" + envelope.getSubject());
logger.debug("Sending Message " + envelope.getContent());
if (envelope.getRecipients().size() == 0 ) {
logger.error("List of recipients is null");
return;
}
Properties props = new Properties();
/**自己邮件服务器配置
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", host);
props.setProperty("mail.user", emailUser);
props.setProperty("mail.password", password);
*/
//QQ邮件服务器
props.put("mail.smtp.host", host);
props.put("mail.smtp.port",port );
props.put("mail.smtp.starttls.enable","true" );
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.socketFactory.port", "993");
// switcher
if(switcher != null && switcher.equals("on")){
//Session mailSession = Session.getDefaultInstance(props, null);//自己邮件服务不需要验证
//QQ邮件服务器,需要验证
Session mailSession = Session.getDefaultInstance(props,new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(emailUser, password);
}
});
/**替换QQ邮件服务器时注释
Transport transport = null;
transport = mailSession.getTransport();
*/
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(displayUserName + "<" + emailUser + ">"));
message.setSentDate(new Date());
try {
message.setSubject(MimeUtility.encodeText(envelope.getSubject(), "UTF-8", "B"));
} catch (UnsupportedEncodingException e) {
logger.error("", e);
}
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(envelope.getContent(), "text/html; charset=\"UTF-8\"");
messageBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
multipart.addBodyPart(messageBodyPart);
if(envelope.getAttachments() != null){
logger.debug("Sending Attachments " + envelope.getAttachments().size());
for(Attachment attachment : envelope.getAttachments()){
String fileName = attachment.getName();
byte[] bytes = attachment.getFile();
logger.debug("Sending Attached file " + fileName);
if(StringUtils.isEmpty(fileName) ||
bytes == null || bytes.length == 0){
continue;
}
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.setFileName(fileName);
ByteArrayDataSource dataSource = new ByteArrayDataSource();
dataSource.setName(fileName);
dataSource.setBytes(bytes);
String contentType =
FileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
dataSource.setContentType(contentType);
logger.info(new StringBuilder()
.append("FileName: ").append(fileName)
.append(" ContentType: ").append(contentType));
attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
multipart.addBodyPart(attachmentBodyPart);
}
}
message.setContent(multipart);
if(envelope.getRecipients() != null){
for (String recipient : envelope.getRecipients()) {
if (recipient != null && !recipient.trim().equals("")) {
logger.warn("Ready to send emails to recipient '" + recipient + "'.");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(recipient));
}
}
}
if(envelope.getCc() != null){
for (String recipient : envelope.getCc()) {
if (recipient != null && !recipient.trim().equals("")) {
logger.warn("Ready to send emails to Cc '" + recipient + "'.");
message.addRecipient(Message.RecipientType.CC,
new InternetAddress(recipient));
}
}
}
if(envelope.getBcc() != null){
for (String recipient : envelope.getBcc()) {
if (recipient != null && !recipient.trim().equals("")) {
logger.warn("Ready to send emails to Bcc '" + recipient + "'.");
message.addRecipient(Message.RecipientType.BCC,
new InternetAddress(recipient));
}
}
}
if (message.getAllRecipients() != null &&
message.getAllRecipients().length != 0) {
try {
logger.info("Sending message.");
/**
transport.connect();替换QQ邮件服务器时注释
transport.sendMessage(message,
message.getAllRecipients());
*/
Transport.send(message,message.getAllRecipients());
logger.info("Message sent.");
} finally {
//transport.close();
}
} else {
logger.error("List of recipients is null");
return;
}
}
}
public void sendEmail(String subject, String content,
Map<String, byte[]> attachments, Boolean preview, String... recipients )
throws MessagingException {
SendingEmailEnvelope envelope = new SendingEmailEnvelope();
envelope.setSubject(subject);
envelope.setContent(content);
envelope.addRecipients(recipients);
if (attachments != null) {
for (String name : attachments.keySet()) {
byte[] file = attachments.get(name);
envelope.addAttachment(name, file);
}
}
if(StringUtils.isNotBlank(content) && preview == false){
sendEmail(envelope);
}
}
@Override
public SendingEmailEnvelope sendEmail(String subject, String templateName, Object[] args,
Map<String, byte[]> attachments, Boolean preview, String... recipients) throws MessagingException {
String subTemp = emailSubjectTemplate.getTemplate(subject, args);
if(subTemp != null){
subject = subTemp;
}
String content = emailContentTemplate.getTemplate(templateName, args);
SendingEmailEnvelope envelope = new SendingEmailEnvelope();
envelope.setSubject(subject);
envelope.setContent(content);
envelope.addRecipients(recipients);
if(attachments != null){
for(String name : attachments.keySet()){
byte[] file = attachments.get(name);
envelope.addAttachment(name, file);
}
}
if(StringUtils.isNotBlank(content) && preview == false){
this.sendEmail(envelope);
}
return envelope;
}
public void setHost(String host) {
this.host = host;
}
public void setEmailUser(String emailUser) {
this.emailUser = emailUser;
}
public void setDisplayUserName(String displayUserName) {
this.displayUserName = displayUserName;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmailSubjectTemplate(MessageTemplate emailSubjectTemplate) {
this.emailSubjectTemplate = emailSubjectTemplate;
}
public void setEmailContentTemplate(MessageTemplate emailContentTemplate) {
this.emailContentTemplate = emailContentTemplate;
}
public MessageTemplate getEmailSubjectTemplate() {
return emailSubjectTemplate;
}
public MessageTemplate getEmailContentTemplate() {
return emailContentTemplate;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public void setSwitcher(String switcher) {
this.switcher = switcher;
}
public static void main(String[] args) throws MessagingException, IOException{
System.out.println("-----send eMial start-----");
SendingEmailUtilImpl email = new SendingEmailUtilImpl();
email.setHost("smtp.exmail.qq.com");
email.setEmailUser("cs@517hk.com");
email.setPassword("szyl517hk");
email.setPort("465");
email.setDisplayUserName("517HK Customer Service");
email.setSwitcher("on");
SendingEmailEnvelope envelope = new SendingEmailEnvelope();
envelope.setSubject("hello");
envelope.setContent("hello");
envelope.addRecipients("82067130@qq.com","45424380@qq.com");
email.sendEmail(envelope);
System.out.println("-----send eMial end-----");
// Map<String, byte[]> attachments = new LinkedHashMap<String, byte[]>();
// InputStream in = new BufferedInputStream(new FileInputStream("C:\\temp\\HotelXo.pdf"));
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// try{
// byte[] buffer = new byte[512];
// int len = in.read(buffer);
// while(len >= 0){
// out.write(buffer, 0, len);
// len = in.read(buffer);
// }
// attachments.put("HotelXo.pdf", out.toByteArray());
// email.sendEmail("hello", "Hello World.", null, "charles.so@222m.net");
// }finally{
// in.close();
// out.close();
// }
}
}