我收到了客户发送的电子邮件,他们在multipart/mixed消息中嵌套了一个multipart/alternative消息。当我获取消息正文时,它只返回multipart/alternative级别的内容,但实际上我想要的是包含在multipart/alternative中的text/html部分。
我查阅了javax.mail的javadocs,但找不到一种简单的方法来获取一个bodypart的内容,特别是它本身就是一个multipart或跳过第一个multipart/mixed部分并进入multipart/alternative体以读取text/html和text/plain部分。
该电子邮件的结构如下:
这是解析电子邮件所用代码的大纲:
我查阅了javax.mail的javadocs,但找不到一种简单的方法来获取一个bodypart的内容,特别是它本身就是一个multipart或跳过第一个multipart/mixed部分并进入multipart/alternative体以读取text/html和text/plain部分。
该电子邮件的结构如下:
...
Content-Type: multipart/mixed;
boundary="----=_Part_19487_1145362154.1418138792683"
------=_Part_19487_1145362154.1418138792683
Content-Type: multipart/alternative;
boundary="----=_Part_19486_1391901275.1418138792683"
------=_Part_19486_1391901275.1418138792683
Content-Transfer-Encoding: 7bit
Content-Type: text/plain; charset=ISO-8859-1
...
------=_Part_19486_1391901275.1418138792683
Content-Transfer-Encoding: 7bit
Content-Type: text/html; charset=ISO-8859-1
...
------=_Part_19486_1391901275.1418138792683--
------=_Part_19487_1145362154.1418138792683--
这是解析电子邮件所用代码的大纲:
Message [] found = fldr.search(searchCondition);
for (int i = 0; i < found.length; i++) {
Message m = found[i];
Object o = m.getContent();
if (o instanceof Multipart) {
log.info("**This is a Multipart Message. ");
Multipart mp = (Multipart)o;
log.info("The Multipart message has " + mp.getCount() + " parts.");
for (int j = 0; j < mp.getCount(); j++) {
BodyPart b = mp.getBodyPart(j);
// Loop if the content type is multipart then get the content that is in that part,
// make it the new container and restart the loop in that part of the message.
if (b.getContentType().contains("multipart")) {
mp = (Multipart)b.getContent();
j = 0;
continue;
}
log.info("This content type is " + b.getContentType());
if(!b.getContentType().contains("text/html")) {
continue;
}
Object o2 = b.getContent();
if (o2 instanceof String) {
<do things with content here>
}
}
}
}
看起来它停留在第二个边界,无法解析更多内容。对于上述消息,它会在boundary="----=_Part_19486_1391901275.1418138792683"处停止,从未到达消息正文。
log.info("This content type is " + b.getContentType());
这段代码会输出什么? - ToYonos