版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011870280/article/details/84373287
之前用java mail获取content都是空,后来发现类型是Multipart,而且里面有好几层
正确的获取邮件正文代码如下
public static String parseMultipart(Multipart multipart) throws MessagingException, IOException {
StringBuffer bodyText = new StringBuffer();
int count = multipart.getCount();
for (int idx = 0; idx < count; idx++) {
BodyPart bodyPart = multipart.getBodyPart(idx);
if (bodyPart.isMimeType("text/plain")) {
bodyText.append(bodyPart.getContent());
} else if (bodyPart.isMimeType("text/html")) {
bodyText.append(bodyPart.getContent());
} else if (bodyPart.isMimeType("multipart/*")) {
Multipart mpart = (Multipart) bodyPart.getContent();
parseMultipart(mpart);
} else if (bodyPart.isMimeType("application/octet-stream")) {
String disposition = bodyPart.getDisposition();
if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
InputStream is = bodyPart.getInputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
copy(is, baos);
bodyText.append(new String(baos.toByteArray()));
}
}
}
return bodyText.toString();
}