[java] java mail 邮件发送工具类

package com.xxx.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
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.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xxx.util.mail.MailEntity;
import com.xxx.util.mail.MailTemplate;
import com.xxx.workflow.util.WorkFlowFunction;

/**
*
* @author Stone Li
*
*/
public class Mail {
private static final Log logger = LogFactory.getLog(Mail.class);
private static Properties mailConfig;

static{
mailConfig = new Properties();
try {
mailConfig.load(Mail.class.getResourceAsStream(“/com/xxx/util/mail/mailconf.properties”));
} catch (IOException e) {
e.printStackTrace();
}
//mailHost=mailConfig.getProperty(“mail.smtp.host”);
//mailUserName=mailConfig.getProperty(“mail.username”);
//mailPassword=mailConfig.getProperty(“mail.password”);

}
//————————————————————————–
@Deprecated
public static String sendMutiMail(List<String> tolist,List<String> cclist,String sendName,String subject,String content,List<String> filepathlist,List<String> imagelist){
return sendMail(tolist, cclist, sendName, subject, content, filepathlist, imagelist);
}
public static String sendMail(List<String> tolist,String sendName,String subject,String content){
return sendMail(tolist,null,sendName,subject,content,null,null);
}
public static String sendMail(List<String> tolist,List<String> cclist,String sendName,String subject,String content){
return sendMail(tolist,cclist,sendName,subject,content,null,null);
}
public static String sendMail(List<String> tolist,List<String> cclist,String sendName,String subject,String content,List<String> filepathlist,List<String> imagelist){
return sendMail(tolist, cclist, null, sendName, subject, content, filepathlist, imagelist);
}

public static String sendMail(List<String> tolist,List<String> cclist,List<String> bcclist,String sendName,String subject,String content,List<String> filepathlist,List<String> imagelist){
return sendMail(new MailEntity(tolist, cclist, bcclist, sendName, subject, content, filepathlist, imagelist));
}

public static String sendMail(MailEntity mailObj){
List<MailEntity> mailList = new ArrayList<MailEntity>();
mailList.add(mailObj);
return sendMail(mailList);
}

/**
* 批量发送邮件
* @param mailList
* @return
*/
public static String sendMail(List<MailEntity> mailList){
try {
List<MimeMessage> msgList = new ArrayList<MimeMessage>();
for(MailEntity msg:mailList){
if(checkEmailAddress(msg)){
MimeMessage message = createMimeMessage(mailConfig.getProperty(“mail.username”),msg.getSendName(),msg.getSubject(),msg.getContent(),
msg.getTolist(),msg.getCclist(),msg.getBcclist(),msg.getFilepathlist(),msg.getImagelist());
logger.info(“@@@sendMail::tolist:”+msg.getTolist()+”,cclist:”+msg.getCclist()+”,bcclist:”+msg.getBcclist()+”,title:”+msg.getSubject());
msgList.add(message);
}else{
return “There is not any email address.”;
}
}
sendMM(msgList);
return “”;
} catch (Exception e) {
e.printStackTrace();
logger.error(“异常:”+e.getMessage());
return e.getMessage();
}
}

private static boolean checkEmailAddress(MailEntity msg){
List<String> tolist = msg.getTolist();
List<String> cclist = msg.getCclist();
List<String> bcclist = msg.getBcclist();
tolist = checkEmailAddress(tolist);
cclist = checkEmailAddress(cclist);
bcclist = checkEmailAddress(bcclist);
msg.setTolist(tolist);
msg.setCclist(cclist);
msg.setBcclist(bcclist);

if((msg.getTolist()!=null && msg.getTolist().size()>0) || (msg.getCclist()!=null && msg.getCclist().size()>0)){
return true;
}else{
return false;
}
//return msg;
}
private static List<String> checkEmailAddress(List<String> emaillist){
if(emaillist==null) return null;
List<String> tolist = new ArrayList<String>();
String regEx = “\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*”;
Pattern pattern = Pattern.compile(regEx);
for(String email:emaillist){
Matcher matcher =pattern.matcher(email);
if(matcher.matches()){
tolist.add(email);
}else{
logger.error(“邮箱格式不正确~”);
}
}
return tolist;
}

private static void sendMM(List<MimeMessage> messages) throws MessagingException{
javax.mail.Session session = javax.mail.Session.getInstance(mailConfig);
//if(!EnvConfig.isProductEnv()) session.setDebug(true);
Transport transport = session.getTransport();
transport.connect(null,mailConfig.getProperty(“mail.username”), mailConfig.getProperty(“mail.password”));
for(MimeMessage message:messages){
transport.sendMessage(message, message.getAllRecipients());
}
transport.close();
}

/**
* 创建并发送复杂html附件(可带附件、图片)
* @param session mail Session
* @param sendMail 发送人邮箱
* @param sendName 发送人
* @param subject 主题
* @param content 邮件内容
* @param tolist 收件人列表
* @param ccList 抄送人列表
* @param filelist 附件列表地址
* @param imagelist 图片列表地址
* @return
* @throws Exception
*/
private static MimeMessage createMimeMessage(String sendMail,
String sendName, String subject, String content,
List<String> tolist, List<String> ccList,
List<String> bccList, List<String> filelist, List<String> imagelist)
throws Exception {
Session session = javax.mail.Session.getInstance(mailConfig);
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称)
message.setFrom(new InternetAddress(sendMail, sendName, “UTF-8”));
// 3. To: 收件人(可以增加多个收件人、抄送、密送)
if(tolist!=null && tolist.size()>0) message.setRecipients(MimeMessage.RecipientType.TO, getAddr(tolist));
if(ccList!=null && ccList.size()>0) message.setRecipients(MimeMessage.RecipientType.CC, getAddr(ccList));
if(bccList!=null && bccList.size()>0) message.setRecipients(MimeMessage.RecipientType.BCC, getAddr(bccList));
// 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题)
if(subject!=null) message.setSubject(subject, “UTF-8”);
// 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)
if ((filelist != null && filelist.size() > 0) || (imagelist != null && imagelist.size() > 0)){
message.setContent(getMimeMultipart(content, filelist, imagelist));
}else{
message.setContent(content, “text/html;charset=UTF-8”);
}
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}

private static InternetAddress[] getAddr(List<String> toList) throws MessagingException {
InternetAddress[] toAddr = new InternetAddress[toList.size()];
for (int i = 0; i < toList.size(); i++) {
toAddr[i] = new InternetAddress(toList.get(i));
}
return toAddr;
}

private static MimeMultipart getMimeMultipart(String content,
List<String> filelist, List<String> imagelist)
throws MessagingException, UnsupportedEncodingException {
// 5.1 正文
MimeBodyPart text = new MimeBodyPart();
text.setContent(content, “text/html;charset=UTF-8”);
MimeMultipart mm = new MimeMultipart();
mm.setSubType(“mixed”);

// 5.2 图片
if (imagelist != null && imagelist.size() > 0) {
MimeMultipart content_imagepart = new MimeMultipart();
MimeMultipart imagemultipart = new MimeMultipart();
for (String attrfile : imagelist) {
MimeBodyPart images = new MimeBodyPart();
FileDataSource fdatasource = new FileDataSource(attrfile);
images.setDataHandler(new DataHandler(fdatasource));
images.setDisposition(MimeBodyPart.INLINE);
images.addHeader(“Content-ID”, MimeUtility
.encodeText(fdatasource.getName()));
images.addHeader(“Content-Type”, “image”);
imagemultipart.addBodyPart(images);

}
// 图片+正文
MimeBodyPart imagebodypart = new MimeBodyPart();
imagebodypart.setContent(imagemultipart);
content_imagepart.addBodyPart(text);
content_imagepart.addBodyPart(imagebodypart);
content_imagepart.setSubType(“related”);
// 5.4 (正文+图片)和附件关系
MimeBodyPart bodycontentpart = new MimeBodyPart();
bodycontentpart.setContent(content_imagepart);
mm.addBodyPart(bodycontentpart);
}

// 5.3 附件
if (filelist != null && filelist.size() > 0) {
MimeBodyPart bodyfilepart = new MimeBodyPart();
MimeMultipart filepart = new MimeMultipart();
for (String attrfile : filelist) {
MimeBodyPart mbpFile = new MimeBodyPart();
FileDataSource fdatasource = new FileDataSource(attrfile);
mbpFile.setDataHandler(new DataHandler(fdatasource));
mbpFile.setFileName(MimeUtility.encodeText(fdatasource.getName()));
filepart.addBodyPart(mbpFile);
}
bodyfilepart.setContent(filepart);
// 5.4 (正文+图片)和附件关系
mm.addBodyPart(text);
mm.addBodyPart(bodyfilepart);
}

return mm;
}

public static List<String> getAdminEmailAddr(){
String[] toListArr = mailConfig.getProperty(“admin.mail”).split(“,”);
List<String> tolist = Arrays.asList(toListArr);
return tolist;
}

@SuppressWarnings(“unchecked”)
public static void saveSendMailList(List<MailEntity> mailList){
List<String> sqlList = new ArrayList<String>();
String sql= “”;
Map<String, String> mailMap = null;
for(MailEntity mail:mailList){
try {
mailMap = BeanUtils.describe(mail);
} catch (Exception e) {
e.printStackTrace();
}
mailMap.remove(“class”);
sql= WorkFlowFunction.makeSaveSQL(mailMap, null, “sent_mail_history”, “id”);
sqlList.add(sql);
}
WorkFlowFunction.executeSQLBatch(sqlList);
}

/**
* 获取邮件模板
* @return
*/
public static Map<String,MailTemplate> getMailModuleMap(){
RecordSetDataSource rsds = WorkFlowFunction.getDBConnection();
String sql=”select id,mouldSubject,mouldtext from DocMailMould”;
List<Map<String,String>> tmplList = WorkFlowFunction.selectListFromDB(rsds, sql, null);

Map<String,MailTemplate> moduleMap = new HashMap<String,MailTemplate>();
for(Map<String,String> map:tmplList){
MailTemplate tmpl = new MailTemplate();
String id = map.get(“id”);
tmpl.setId(id);
tmpl.setSubject(map.get(“mouldSubject”));
tmpl.setText(map.get(“mouldtext”));

tmpl.setId(map.get(“id”));
moduleMap.put(id, tmpl);
}
return moduleMap;
}

/**
* 获取邮件模板
* @return
*/
public static MailTemplate getMailModuleMap(String id){
Map<String,MailTemplate> moduleMap = getMailModuleMap();
return moduleMap.get(id);
}

public static MailEntity pkgMail(MailTemplate template,Map<String,Object> datas,List<String> tolist){
List<List<String>> receiveList = new ArrayList<List<String>>();
receiveList.add(tolist);
receiveList.add(null);
receiveList.add(null);
return packageMail(template, datas, receiveList);
}

public static MailEntity packageMail(MailTemplate template,Map<String,Object> datas,List<List<String>> receiveList){
String subjectTemp = template.getSubject();
String contentTemp = template.getText();
contentTemp+=”<div></div><div><span style=\”color: rgb(255, 0, 0);\”>温馨提示:此邮件由系统自动发出,请勿回复!</span></div>”;
// 解析字符串模板的方法,并返回处理后的字符串
String subject = FreeMarkerUtil.processStringTemplate(subjectTemp, datas, null);
String content = FreeMarkerUtil.processStringTemplate(contentTemp, datas, null);
return new MailEntity(receiveList.get(0), receiveList.get(1), receiveList.get(2),”管理员”, subject, content, null, null);
}

// public static void main(String[] args) {
// List<String> tolist = new ArrayList<String>();
// tolist.add(“xx@xx.com”);
// List<String> cclist = new ArrayList<String>();
// String sendName = null;
// String subject = “test001″;
//
// //String content =”<img src=’D:/stone/aaa.jpg’/>content…..”;
// List<String> filepathlist = new ArrayList<String>();
// filepathlist.add(“D:/work_line/JDK/LICENSE”);
// List<String> imagelist = new ArrayList<String>();
// imagelist.add(“d:/stone/aaa.jpg”);
//
// FileDataSource fdatasource = new FileDataSource(“d:/stone/aaa.jpg”);
// logger.info(fdatasource);
// String content = “<img src='”+fdatasource.getName()+”‘/>aaaaaaa”; //内容
//
//
// Mail.sendMail(tolist, cclist, sendName, subject, content, null, imagelist);
// }

}

//———————————————————————————————————————————-

package com.xxx.util.mail;

import java.util.List;

public class MailEntity {
private List<String> tolist;
private List<String> cclist;
private List<String> bcclist;
private String sendName;
private String subject;
private String content;
private List<String> filepathlist;
private List<String> imagelist;
private String remark;

public MailEntity(List<String> tolist, List<String> cclist,
List<String> bcclist, String sendName, String subject,
String content, List<String> filepathlist, List<String> imagelist) {
super();
this.tolist = tolist;
this.cclist = cclist;
this.bcclist = bcclist;
this.sendName = sendName;
this.subject = subject;
this.content = content;
this.filepathlist = filepathlist;
this.imagelist = imagelist;
}
public List<String> getTolist() {
return tolist;
}
public List<String> getCclist() {
return cclist;
}
public String getSendName() {
return sendName;
}
public String getSubject() {
return subject;
}
public String getContent() {
return content;
}
public List<String> getFilepathlist() {
return filepathlist;
}
public List<String> getImagelist() {
return imagelist;
}
public void setTolist(List<String> tolist) {
this.tolist = tolist;
}
public void setCclist(List<String> cclist) {
this.cclist = cclist;
}
public void setSendName(String sendName) {
this.sendName = sendName;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setContent(String content) {
this.content = content;
}
public void setFilepathlist(List<String> filepathlist) {
this.filepathlist = filepathlist;
}
public void setImagelist(List<String> imagelist) {
this.imagelist = imagelist;
}
public List<String> getBcclist() {
return bcclist;
}
public void setBcclist(List<String> bcclist) {
this.bcclist = bcclist;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}

}

//———————————————————————————————————————————-

package com.xxx.util.mail;

public class MailTemplate {
private String id;
private String subject;
private String text;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public String getText() {
return text;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setText(String text) {
this.text = text;
}

}

//———————————————————————————————————————————-

/util/mail/mailconf.properties

mail.transport.protocol=smtp
#mail.smtp.host=0.0.0.0
mail.smtp.host=xxx.com
mail.smtp.auth=true
mail.username=xxx@xxx.com
mail.password=000000000

admin.mail=admin@admin.com

留下评论