这个工具类用于在使用Java Mail时,对message的内容提取,使提取我们所需要的内容更加方便,其中需要注意的点是:
其中保存附件的方法(将附件可以保存在本地或者服务器中)。
public class PraseMimeMessage {
private MimeMessage mimeMessage = null;
private String saveAttachPath = "";
private StringBuffer bodytext = new StringBuffer();
private String dateformat = "yy-MM-dd HH:mm";
private ArrayList<String> attachments = new ArrayList();
private ArrayList<Long> attachSizeList = new ArrayList();
private ArrayList<String> cidList = new ArrayList();
public PraseMimeMessage() {
}
public PraseMimeMessage(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}
/**
* 邮箱来处
* */
public String getFrom()
throws Exception {
if (this.mimeMessage != null) {
InternetAddress[] address = (InternetAddress[]) this.mimeMessage.getFrom();
if (address.length < 1) {
return "";
}
String from = address[0].getAddress();
if (from == null) {
from = "";
}
String personal = address[0].getPersonal();
if (personal == null) {
personal = "";
}
String fromaddr = personal + "<" + from + ">";
return fromaddr;
}
return "";
}
/**
* 获取邮件地址
* */
public String getMailAddress(String type)
throws Exception {
String mailaddr = "";
if (this.mimeMessage != null) {
String addtype = type.toUpperCase();
InternetAddress[] address = null;
if (("TO".equals(addtype)) || ("CC".equals(addtype)) || ("BCC".equals(addtype))) {
if ("TO".equals(addtype))
address = (InternetAddress[]) this.mimeMessage.getRecipients(Message.RecipientType.TO);
else if ("CC".equals(addtype))
address = (InternetAddress[]) this.mimeMessage.getRecipients(Message.RecipientType.CC);
else {
address = (InternetAddress[]) this.mimeMessage.getRecipients(Message.RecipientType.BCC);
}
if ((address != null) && (address.length > 0)) {
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 = mailaddr + "," + compositeto;
}
mailaddr = mailaddr.substring(1);
}
} else {
throw new Exception("Error emailaddr type!");
}
}
return mailaddr;
}
/**
* 获取目录
* */
public String getSubject()
throws MessagingException {
String subject = "";
if (this.mimeMessage != null)
try {
subject = MimeUtility.decodeText(this.mimeMessage.getSubject());
if (subject == null)
subject = "";
} catch (Exception localException) {
}
return subject;
}
/**
* 信息日期
* */
public Date getSentDate() {
Date sentdate = new Date();
try {
if (this.mimeMessage != null)
sentdate = this.mimeMessage.getSentDate();
} catch (MessagingException e) {
e.printStackTrace();
}
SimpleDateFormat format = new SimpleDateFormat(this.dateformat);
return sentdate;
}
public String getBodyText() {
return this.bodytext.toString();
}
/**
* 获取邮件文本
* */
public void getMailContent(Part part)
throws Exception {
String contenttype = part.getContentType();
if (contenttype.startsWith("text/plain")) {
getMailTextContent(part, true);
} else {
getMailTextContent(part, false);
}
}
/**
* 文本内容信息
* */
public void getMailTextContent(Part part, boolean plainFlag)
throws MessagingException, IOException {
boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
if ((part.isMimeType("text/html")) && (!isContainTextAttach) && (!plainFlag)) {
this.bodytext.append(MimeUtility.decodeText(part.getContent().toString()));
} else if ((part.isMimeType("text/plain")) && (!isContainTextAttach) && (plainFlag)) {
this.bodytext.append(part.getContent().toString());
plainFlag = false;
} else if (part.isMimeType("message/rfc822")) {
getMailTextContent((Part) part.getContent(), plainFlag);
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int partCount = multipart.getCount();
for (int i = 0; i < partCount; ++i) {
BodyPart bodyPart = multipart.getBodyPart(i);
getMailTextContent(bodyPart, plainFlag);
}
}
}
/**
* 获取信息ID
* */
public String getMessageId()
throws MessagingException {
if (this.mimeMessage != null) {
return this.mimeMessage.getMessageID();
}
return null;
}
/**
* 确定是否为新文件
* */
public boolean isNew()
throws MessagingException {
boolean isnew = false;
if (this.mimeMessage != null) {
Flags flags = this.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;
}
/**
* 附加标志
*/
public boolean isContainAttach(Part part)
throws Exception {
boolean attachflag = false;
if (part != null) {
String contentType = part.getContentType();
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("attachment"))) {
attachflag = true;
} else {
if ((disposition != null) &&
(disposition.equals("inline")))
continue;
if (mpart.isMimeType("multipart/*")) {
attachflag = isContainAttach(mpart);
} else {
String contype = mpart.getContentType();
if (contype.toLowerCase().indexOf("application") != -1) {
attachflag = true;
}
if (contype.toLowerCase().indexOf("name") != -1)
attachflag = true;
}
}
}
} else if (part.isMimeType("message/rfc822")) {
attachflag = isContainAttach((Part) part.getContent());
}
}
return attachflag;
}
/**
* 保存附件
*/
public String saveAttachMent(Part part) throws Exception {
System.out.println("login......saveAttachMent................");
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();
System.out.println("打印拿到的附件名称------------------" + fileName);
System.out.println("经过mimeUtility解码后得到的:" + MimeUtility.decodeText(fileName));
//关键点:-----------------经过mimeUtility解码后可以得到正确的附件名称
// System.out.println("经过base64进行解码得到的:"+base64Decoder(fileName));
if (fileName.toLowerCase().indexOf("utf") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
System.out.println("进行存储附件前的文件名称(1):" + fileName);
return saveFile(fileName, mpart.getInputStream());
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart);
} else {
fileName = mpart.getFileName();
if ((fileName != null) && (fileName.toLowerCase().indexOf("utf") != -1)) {
fileName = MimeUtility.decodeText(fileName);
System.out.println("进行存储附件前的文件名称(2):" + fileName);
return saveFile(fileName, mpart.getInputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachMent((Part) part.getContent());
}
return null;
}
//填写附件存入路径---------------------1
public void setAttachPath(String attachpath) {
this.saveAttachPath = attachpath;
}
public void setDateFormat(String format)
throws Exception {
this.dateformat = format;
}
public String getAttachPath() {
return this.saveAttachPath;
}
/**
* 保存附件到指定目录
*/
private String saveFile(String fileName, 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 = "c:\\tmp";
} else {
separator = "/";
storedir = "/tmp";
}*/
File storefile = new File(getAttachPath()+ fileName);
System.out.println("storefile's path: " + storefile.toString());
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();
}
return storefile.toString();
} catch (Exception exception) {
exception.printStackTrace();
throw new Exception("文件保存失败!");
} finally {
bos.close();
bis.close();
}
}
public void resetList() {
this.attachments.clear();
this.attachSizeList.clear();
this.cidList.clear();
}
}