package com.primeton.esb.component.email.utils;
import java.io.File;
/**
* 附件的对象
*
* @author yangenxiong yangenxiong2009@gmail.com
* @version 1.0
* <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
* <br>Copyright (C), 2009-2010, yangenxiong
* <br>This program is protected by copyright laws.
*/
public class FileObject
{
//源文件名字
private String sourceName;
//对应的文件
private File file;
public FileObject(String sourceName, File file) {
this.sourceName = sourceName;
this.file = file;
}
public String getSourceName() {
return sourceName;
}
public void setSourceName(String sourceName) {
this.sourceName = sourceName;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
@Override
public String toString() {
return this.sourceName;
}
}
/**
* @Title: ReceiveMail.java
* @Description: TODO
* @author ZhangHuan
* @date 2014-2-25 上午9:04:44
* @version V1.0
*/
/**
* @Description: TODO
* @author ZhangHuan
* @date 2014-2-25 上午9:04:44
*/
package com.primeton.esb.component.email.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.AndTerm;
import javax.mail.search.BodyTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SentDateTerm;
import javax.mail.search.SubjectTerm;
/**
*
* @Description: TODO
* @author ZhangHuan
* @date 2014-3-12 上午10:27:00
*/
public class MailUtils
{
/*protected ILogger logger = LoggerFactory.getInstance()
.getLogger(getClass());*/
private final String SSL_FACTORY
= "javax.net.ssl.SSLSocketFactory";
public MailUtils()
{
}
/**
* @throws Exception
*
* @Title: getStore
* @Description: 根据不同参数获得不同的协议store,pop3 imap
* @param @param protocol
* @param @return
* @return Store
* @throws
*/
public Store getStore(String protocol,String host,int port,String userName,String password,Store store) throws Exception {
if(protocol!=null&&!"".equals(protocol)){
if("pop3".equalsIgnoreCase(protocol)){
if (store == null || !store.isConnected()) {
try {
Properties props = new Properties();
if (isGmail(userName)) {
props.setProperty("mail.pop3.socketFactory.class",
SSL_FACTORY);
}
// 创建mail的Session
Session session = Session.getInstance(props);
// 使用pop3协议接收邮件
URLName url = new URLName(protocol, host, port, null,
userName, password);
// 得到邮箱的存储对象
store = session.getStore(url);
//logger.debug("pop3 connect email success");
//store.connect();
} catch (Exception e) {
//e.printStackTrace();
//logger.error(" pop3 get store fail:"+e.getMessage());
throw new Exception(" pop3 get store fail:"+e.getMessage());
}
}
}else{
// 准备连接服务器的会话信息
Properties props = new Properties();
props.setProperty("mail.store.protocol", protocol);
props.setProperty("mail.imap.host", host);
props.setProperty("mail.imap.port",port+"");
/* props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.host", "imap.163.com");
props.setProperty("mail.imap.port", "143"); */
// 创建Session实例对象
Session session = Session.getInstance(props);
// 创建IMAP协议的Store对象
try {
store = session.getStore("imap");
//store.connect(userName,password);
//logger.debug("pop3 connect email success");
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
throw new Exception(" imap get store fail:"+e.getMessage());
}
}
}
return store;
}
/**
* 获得邮件主题
*/
public String getSubject(Message mimeMessage) throws MessagingException {
String subject = "";
try {
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null)
subject = "";
} catch (Exception exce) {}
return subject;
}
/**
* 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
*/
public boolean getReplySign(Message mimeMessage) throws MessagingException {
boolean replysign = false;
String needreply[] = mimeMessage
.getHeader("Disposition-Notification-To");
if (needreply != null) {
replysign = true;
}
return replysign;
}
/**
* 获得邮件发送日期
*/
public String getSentDate(Message mimeMessage) throws Exception {
Date sentdate = mimeMessage.getSentDate();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
return format.format(sentdate);
}
/**
* 获得此邮件的Message-ID
*/
public int getMessageId(Message mimeMessage) throws MessagingException {
return mimeMessage.getMessageNumber();
}
/**
* 获得此邮件的charset
*/
public String getContentType(Message mimeMessage) throws MessagingException {
return mimeMessage.getContentType();
}
//得到接收的日期, 优先返回发送日期, 其次返回收信日期
public Date getReceivedDate(Message m)
throws Exception
{
/*if (m.getSentDate() != null)
return m.getSentDate();*/
if (m.getReceivedDate() != null)
return m.getReceivedDate();
return new Date();
}
//得到抄送的地址
public List<String> getCC(Message m)
throws Exception
{
Address[] addresses = m.getRecipients(
Message.RecipientType.CC);
return getAddresses(addresses);
}
//得到文件名的后缀
public String getFileSuffix(String fileName)
{
if (fileName == null || fileName.trim().equals(""))
return "";
int dotPos = fileName.lastIndexOf(".");
if (dotPos != -1)
{
return fileName.substring(dotPos);
}
return "";
}
//获得邮件的附件
public List<FileObject> getFiles(Message m)
throws Exception
{
List<FileObject> files = new ArrayList<FileObject>();
//是混合类型, 就进行处理
if (m.isMimeType("multipart/mixed"))
{
Multipart mp = (Multipart)m.getContent();
//得到邮件内容的Multipart对象并得到内容中Part的数量
int count = mp.getCount();
for (int i = 1; i < count; i++)
{
//获取附件
Part part = mp.getBodyPart(i);
//获取邮件附件名
String serverFileName = MimeUtility
.decodeText(part.getFileName());
//生成UUID作为在本地系统中唯一的文件标识
String fileName = UUID.randomUUID().toString();
File file = new File(fileName
+ getFileSuffix(serverFileName));
//读写文件
FileOutputStream fos = new FileOutputStream(file);
InputStream is = part.getInputStream();
BufferedOutputStream outs = new BufferedOutputStream(fos);
//使用IO流读取邮件附件
byte[] b = new byte[1024];
int hasRead = 0;
while((hasRead = is.read(b)) > 0)
{
outs.write(b , 0 , hasRead);
}
outs.close();
is.close();
fos.close();
//封装对象
FileObject fileObject = new FileObject(serverFileName, file);
files.add(fileObject);
}
}
return files;
}
//处理邮件正文的工具方法
private StringBuffer getContent(Part part
, StringBuffer result) throws Exception
{
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
//System.out.println("CONTENTTYPE: " + contenttype);
if (part.isMimeType("multipart/*"))
{
Multipart p = (Multipart)part.getContent();
int count = p.getCount();
//Multipart的第一部分是text/plain,
//第二部分是text/html的格式, 只解析第一部分即可
if (count > 1) count = 1;
for(int i = 0; i < count; i++)
{
BodyPart bp = p.getBodyPart(i);
//递归调用
getContent(bp, result);
}
}
else if (part.isMimeType("text/*")&&!conname)
{
//遇到文本格式或者html格式, 直接得到内容
result.append(part.getContent());
}else if (part.isMimeType("message/rfc822")) {
getContent((Part) part.getContent(),result);
}
return result;
}
//返回邮件正文内容
public StringBuffer getContent(Message m)
throws Exception
{
StringBuffer sb = new StringBuffer("");
return getContent(m , sb);
}
//得到一封邮件的所有收件人
public List<String> getAllRecipients(Message m)
throws Exception
{
Address[] addresses = m.getAllRecipients();
return getAddresses(addresses);
}
//工具方法, 将参数的地址字符串封装成集合
public List<String> getAddresses(Address[] addresses)
{
List<String> result = new ArrayList<String>();
if (addresses == null) return result;
//遍历Address[]数组,将每个元素转换为字符串后收集起来
for (Address a : addresses)
{
result.add(a.toString());
}
return result;
}
//得到发送人的地址
public String getSender(Message m)
throws Exception
{
Address[] addresses = m.getFrom();
return MimeUtility.decodeText(addresses[0].toString());
}
/**
* 判断此邮件是否已读,如果未读返回返回false,反之返回true
*/
@SuppressWarnings("unused")
private boolean isNew(Message mimeMessage) throws MessagingException {
boolean isnew = false;
Flags flags = mimeMessage.getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
for (int i = 0; i < flag.length; i++) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true;
break;
}
}
return isnew;
}
/**
* @throws Exception
*
* @Title: writeOut
* @Description: 将邮件的唯一iD保存起来针对pop3
* @param @param uidList
* @param @return
* @return boolean
* @throws
*/
public boolean writeOut (ArrayList<String> uidList,String saveFilePath,boolean flag) throws Exception {
StringBuffer strBuf = new StringBuffer();
if (uidList != null && !uidList.isEmpty()) {
for (String str : uidList) {
strBuf.append(str);
strBuf.append(";");
}
}
String strUid = strBuf.substring(0, strBuf.lastIndexOf(";"));
FileWriter write = null;
try {
File file =null;
if(flag){
file= new File(saveFilePath+"email_endpoint_ID.txt");
}
if(!flag){
file= new File(saveFilePath+"email_ID.txt");
}
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
write = new FileWriter(file, false);
write.write(strUid);
write.flush();
write.close();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new Exception("write pop3 message id fail"+e.getMessage());
}
return false;
}
/**
* @throws Exception
*
* @Title: readIn
* @Description: 从本地读取已经保存的邮件id 针对pop3
* @param @return
* @return ArrayList<String>
* @throws
*/
public ArrayList<String> readIn(String saveFilePath,boolean flag) throws Exception {
ArrayList<String> uidList = new ArrayList<String>();
String uidStr = "";
StringBuffer strBuf = new StringBuffer();
FileReader fr = null;
BufferedReader bReader = null;
File file =null;
if(flag){
file= new File(saveFilePath+"email_endpoint_ID.txt");
}
if(!flag){
file= new File(saveFilePath+"email_ID.txt");
}
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new Exception("readIn message UID fail file createNewFile fail"+e.getMessage());
}
}
try {
fr = new FileReader(file);
bReader = new BufferedReader(fr);
while ((uidStr = bReader.readLine()) != null) {
strBuf.append(uidStr);
}
bReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new Exception("readIn message UID fail"+e.getMessage());
}
if (strBuf.toString().contains(";")) {
String[] uid = strBuf.toString().split(";");
for (int i = 0; i < uid.length; i++) {
uidList.add(uid[i]);
}
return uidList;
}
if (!strBuf.toString().contains(";") && strBuf.toString().length() != 0) {
uidList.add(strBuf.toString());
return uidList;
}
return uidList;
}
/**
* 【保存附件】
*/
public void saveAttachMent(Part part,String storedir) throws Exception {
String fileName = "";
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE)))) {
fileName = mpart.getFileName();
if (fileName.toLowerCase().indexOf("gb2312") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
saveFile(fileName, storedir,mpart.getInputStream());
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart ,storedir);
} else {
fileName = mpart.getFileName();
if ((fileName != null)
&& (fileName.toLowerCase().indexOf("GB2312") != -1)) {
fileName = MimeUtility.decodeText(fileName);
saveFile(fileName, storedir,mpart.getInputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachMent((Part) part.getContent(),storedir);
}
}
/**
* 【真正的保存附件到指定目录里】
*/
@SuppressWarnings("null")
private void saveFile(String fileName, String storedir ,InputStream in) throws Exception {
String osName = System.getProperty("os.name");
//String storedir = getAttachPath();
String separator = "";
if (osName == null)
osName = "";
if (osName.toLowerCase().indexOf("win") != -1) {
separator = "\\";
if (storedir != null || !storedir.equals(""))
storedir = "D:\\tmp";
} else {
separator = "/";
storedir = "/tmp";
}
File storefile = new File(storedir + separator + fileName);
/* if (!storefile.exists()) {
storefile.mkdir();
}*/
System.out.println("storefile's path: " + storefile.toString());
// for(int i=0;storefile.exists();i++){
// storefile = new File(storedir+separator+fileName+i);
// }
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storefile));
bis = new BufferedInputStream(in);
int c;
while ((c = bis.read()) != -1) {
bos.write(c);
bos.flush();
}
} catch (Exception exception) {
exception.printStackTrace();
throw new Exception("文件保存失败!");
} finally {
bos.close();
bis.close();
}
}
/**
* 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
*/
public String getMailAddress(String type ,Message mimeMessage) throws Exception {
String mailaddr = "";
String addtype = type.toUpperCase();
InternetAddress[] address = null;
if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {
if (addtype.equals("TO")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
} else if (addtype.equals("CC")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
}
if (address != null) {
for (int i = 0; i < address.length; i++) {
String email = address[i].getAddress();
if (email == null)
email = "";
else {
email = MimeUtility.decodeText(email);
}
String personal = address[i].getPersonal();
if (personal == null)
personal = "";
else {
personal = MimeUtility.decodeText(personal);
}
String compositeto = personal + "<" + email + ">";
mailaddr += "," + compositeto;
}
mailaddr = mailaddr.substring(1);
}
} else {
throw new Exception("Error emailaddr type!");
}
return mailaddr;
}
public void writeFile(String filePath,StringBuffer content) throws Exception{
File file=new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if(!file.exists()){
file.createNewFile();
}
FileWriter pw = new FileWriter(file);
pw.write(content.toString());
pw.close();
}
/**
* @throws Exception
*
* @Title: getSearcherMailTerm
* @Description: 根据条件查询邮件的通用方法
* @param @return
* @return SearchTerm
* @throws
*/
public SearchTerm getSearcherMailTerm(String subject_term,String body_term,String first_date,String second_date) throws Exception{
SearchTerm sub_term=null;
SearchTerm bo_term=null;
SearchTerm comparisonTermGe = null;
SearchTerm comparisonTermLe = null;
ArrayList <SearchTerm> terms_list=new ArrayList<SearchTerm>();
if(subject_term!=null&&!"".equals(subject_term)){
sub_term=new SubjectTerm(subject_term);
}
if(body_term!=null&&!"".equals(body_term)){
bo_term=new BodyTerm(body_term);
}
if(first_date!=null&&!"".equals(first_date)&&second_date!=null&&!"".equals(second_date)){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
Date firstDate=null;
Date secondDate=null;
try {
firstDate = df.parse(first_date);
secondDate = df.parse(second_date);
} catch (ParseException e) {
// TODO Auto-generated catch block
throw new Exception("getSearcherMailTerm error:" +e.getMessage());
//logger.error(e.getMessage());
}
comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, firstDate);
comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, secondDate);
}
if(sub_term!=null){
terms_list.add(sub_term);
}
if(bo_term!=null){
terms_list.add(bo_term);
}
if(comparisonTermGe!=null){
terms_list.add(comparisonTermGe);
}
if(comparisonTermLe!=null){
terms_list.add(comparisonTermLe);
}
SearchTerm [] terms=new SearchTerm[terms_list.size()];
for(int i=0;i<terms_list.size();i++){
terms[i]=terms_list.get(i);
}
SearchTerm andTerms=new AndTerm(terms);
return andTerms;
}
/**
*
* @Title: isGmail
* @Description:对于Gmail邮箱系统需要特别处理
* @param @return
* @return boolean
* @throws
*/
public boolean isGmail(String userName) {
if (userName == null || userName.trim().equals(""))
return false;
if (userName.lastIndexOf("@gmail.com") != -1) {
return true;
}
return false;
}
/* *//**
* 发送邮件
*
* @param sender
* 发送邮箱
* @param password
* 发送邮箱密码
* @param receivers
* 接受者邮箱
* @param title
* 邮件标题
* @param mailContent
* 邮件内容
* @param attachements
* 附件
* @param mimetype
* 对象的MIME类型
* @param charset
* 字符集
* @throws ESBAdapterException
*//*
public String sendEmail(String smtpHost, final String user,
final String password, String title, String mailContent,
File[] attachements, String mimetype, String charset, String bcc,
String cc, String receivers) throws Exception {
// 创建邮件Session所需的Properties对象
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp"); // smtp协议
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true");
// 创建Session对象
Session session = Session.getInstance(props
// 以匿名内部类的形式创建登录服务器的认证对象
, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
try {
//使用session创建MIME类型的消息
MimeMessage mimeMessage = new MimeMessage(session);
//设置发件人邮件
mimeMessage.setFrom(new InternetAddress(user));
//获取所有收件人邮箱地址
if(receivers!=null&&!"".equals(receivers)){
if(receivers.contains(";")){
InternetAddress[] receiver = new InternetAddress[receivers.split(";").length];
for (int i=0; i<receivers.split(";").length; i++) {
receiver[i] = new InternetAddress(receivers.split(";")[i]);
}
//设置收件人邮件
mimeMessage.setRecipients(Message.RecipientType.TO, receiver);
}else{
InternetAddress[] receive={new InternetAddress(receivers)};
//设置收件人邮件
mimeMessage.setRecipients(Message.RecipientType.TO, receive);
}
}
if (bcc != null && !bcc.equals("")) {
InternetAddress[] bccAddress = InternetAddress.parse(bcc);
mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddress);
}
if (cc != null && !cc.equals("")) {
InternetAddress[] ccAddress = InternetAddress.parse(cc);
mimeMessage.setRecipients(Message.RecipientType.CC, ccAddress);
}
//设置标题
mimeMessage.setSubject(title, charset);
//设置邮件发送时间
//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//mimeMessage.setSentDate(format.parse("2011-12-1"));
mimeMessage.setSentDate(new Date());
//创建附件
Multipart multipart = new MimeMultipart();
//创建邮件内容
MimeBodyPart body = new MimeBodyPart();
//设置邮件内容
body.setContent(mailContent, (mimetype!=null && !"".equals(mimetype) ? mimetype : "text/plain")+ ";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);
}
}
//设置邮件内容(使用Multipart方式)
mimeMessage.setContent(multipart);
//发送邮件
Transport.send(mimeMessage);
// 发送邮件
// Transport transport = session.getTransport("smtp");
// 连接服务器的邮箱
// transport.connect(smtpHost, sender, password);
// 把邮件发送出去
// transport.sendMessage(mimeMessage,
// mimeMessage.getAllRecipients());
// transport.close();
return "email_success";
} catch (Exception e) {
logger.error("AbstractEmailEndpointComponent sendEmail error: ", e);
return "email_error";
}
}
*/
}
此类 根据自己情况而写
public void receiverMessage() {
ArrayList<Message> messageList = null;
StringBuffer saveFilePath= new StringBuffer(System.getProperty(IConstants.TIP_HOME)+File.separator + "EOS" + File.separator
+ "_srv"+File.separator +"work"+File.separator+"mail"+File.separator);
// StringBuffer content=new StringBuffer();
boolean flag = false;
POP3Folder folder =null;
try {
folder = (POP3Folder) store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
messageList=new ArrayList<Message>();
Message messages[]=folder.search(mailUtils.getSearcherMailTerm(subject_term,body_term,first_date,second_date));
if(messages.length==0){
try {
if (folder != null&&folder.isOpen())
folder.close(false);
} catch (MessagingException e) {
// TODO Auto-generated catch block
logger.error("AbstractEmailTransportComponent folder close fail :"+ e.getMessage());
}
logger.debug("AbstractEmailTransport the message is empty !");
return;
}
if(message_type==1){
ArrayList <String> uidList=mailUtils.readIn(saveFilePath.toString(),false);
String ui = "";
for (int i = 0; i < messages.length; i++) {
ui = folder.getUID(messages[i]);
if (uidList.size() != 0) {
for (int j = 0; j < uidList.size(); j++) {
if (uidList.get(j).toString().equals(ui)) {
// uidList.add(ui);
flag = true;
break;
}// end in if
}// end in for
if (!flag) {
messageList.add(messages[i]);
uidList.add(ui);
}
flag = false;
} else {
messageList.add(messages[i]);
uidList.add(ui);
}
}// for end
mailUtils.writeOut(uidList,saveFilePath.toString(),false);
}//if end
if(message_type==2){//all mail revice
ArrayList <String> uidList=new ArrayList<String>();
for (int i = 0; i < messages.length; i++) {
uidList.add(folder.getUID(messages[i]));
messageList.add(messages[i]);
}
mailUtils.writeOut(uidList,saveFilePath.toString(),false);
}
if(messageList.size()==0){
try {
if (folder != null&&folder.isOpen())
folder.close(false);
} catch (MessagingException e) {
// TODO Auto-generated catch block
logger.error("AbstractEmailTransportComponent folder close fail :"+ e.getMessage());
}
logger.debug("AbstractEmailTransport the message is empty !");
return;
}
for (int i = 0; i < messageList.size(); i++) {
/*content=mailUtils.getContent(messageList.get(i));
//获得邮件名称
saveFilePath= saveFilePath.append(mailUtils.getSubject(messageList.get(i))+".txt");
mailUtils.writeFile(saveFilePath.toString(), content);
saveFilePath=saveFilePath.replace(0,saveFilePath.capacity(),saveFilePath.substring(0, saveFilePath.toString().lastIndexOf(File.separator)+1));*/
if(msgsend){
this.doRequestHandler(messageList.get(i));
}
}
}catch(Exception e){
logger.error("AbstractEmailTransportComponent receiverMessage error: ",
e);
}
}
/**
* 发送邮件
*
* @param sender
* 发送邮箱
* @param password
* 发送邮箱密码
* @param receivers
* 接受者邮箱
* @param title
* 邮件标题
* @param mailContent
* 邮件内容
* @param attachements
* 附件
* @param mimetype
* 对象的MIME类型
* @param charset
* 字符集
* @throws ESBAdapterException
*/
public boolean sendEmail(String smtpHost, final String user,
final String password, String title, String mailContent,
File[] attachements, String mimetype, String charset, String bcc,
String cc, String receivers) throws Exception {
//设置smtp服务器地址
//这里使用QQ邮箱,记得关闭独立密码保护功能和在邮箱中设置POP3/IMAP/SMTP服务
/* props.put("mail.smtp.host", "smtp.sina.com");
//需要验证
props.put("mail.smtp.auth", "true");*/
// 创建邮件Session所需的Properties对象
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true");
// 创建Session对象
Session session = Session.getInstance(props
// 以匿名内部类的形式创建登录服务器的认证对象
, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
try {
//使用session创建MIME类型的消息
MimeMessage mimeMessage = new MimeMessage(session);
//设置发件人邮件
mimeMessage.setFrom(new InternetAddress(user));
//获取所有收件人邮箱地址
if(receivers!=null&&!"".equals(receivers)){
if(receivers.contains(";")){
InternetAddress[] receiver = new InternetAddress[receivers.split(";").length];
for (int i=0; i<receivers.split(";").length; i++) {
receiver[i] = new InternetAddress(receivers.split(";")[i]);
}
//设置收件人邮件
mimeMessage.setRecipients(Message.RecipientType.TO, receiver);
}else{
InternetAddress[] receive={new InternetAddress(receivers)};
//设置收件人邮件
mimeMessage.setRecipients(Message.RecipientType.TO, receive);
}
}
if (bcc != null && !bcc.equals("")) {
InternetAddress[] bccAddress = InternetAddress.parse(bcc);
mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddress);
}
if (cc != null && !cc.equals("")) {
InternetAddress[] ccAddress = InternetAddress.parse(cc);
mimeMessage.setRecipients(Message.RecipientType.CC, ccAddress);
}
if(charset==null||"".equals(charset)){
charset="GBK";
}
if(charset.contains("multipart/alternative")){
charset="GBK";
}
//设置标题
mimeMessage.setSubject(title, charset);
//设置邮件发送时间
//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//mimeMessage.setSentDate(format.parse("2011-12-1"));
mimeMessage.setSentDate(new Date());
//创建附件
Multipart multipart = new MimeMultipart();
//创建邮件内容
MimeBodyPart body = new MimeBodyPart();
//设置邮件内容
body.setContent(mailContent, (mimetype!=null && !"".equals(mimetype) ? mimetype : "text/plain")+ ";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);
}
}*/
//设置邮件内容(使用Multipart方式)
mimeMessage.setContent(multipart);
//发送邮件
Transport.send(mimeMessage);
return true;
} catch (Exception e) {
logger.error("AbstractEmailEndpointComponent sendEmail error: ", e);
return false;
}
}