原因:很多邮件工具在发送HTML邮件的时候,为了防止接收端无法阅读html邮件,都附送了一份纯文本的邮件。解析的时候需要对这种情况进行过滤。
办法:写一变量,且优先读取html邮件,当读取过html邮件,则不再解析text/plain内容。只有text/plain内容时正常显示。
小例子:
public StringBuffer getMailContent(Part part, StringBuffer bodytext)
throws MessagingException, IOException {
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
if (part.isMimeType("text/html")&& !conname) {
bodytext.append((String)part.getContent());
}else if(part.isMimeType("text/plain")&& !conname){
bodytext.append((String)part.getContent());
}else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int count = multipart.getCount();
boolean hasHtml = checkHasHtml(multipart);//这里校验是否有text/html内容
for(int index = 0 ; index < count ; index++ ){
Part temp = multipart.getBodyPart(index);
if(temp.isMimeType("text/plain")&&hasHtml){
//有html格式的则不显示无格式文档的内容
}else{
getMailContent(temp, bodytext);
}
}
}else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent(), bodytext);
}else{}
return bodytext;
}
public boolean checkHasHtml(Multipart part) throws MessagingException, IOException{
boolean hasHtml = false;
int count = part.getCount();
for(int i = 0 ; i < count ; i++ ){
Part bodyPart = part.getBodyPart(i);
if (bodyPart.isMimeType("text/html")) {
hasHtml = true;
break;
}
}
return hasHtml;
}