从 JavaMail 消息中预取预览文本

2022-01-20 00:00:00 imap fetch java jakarta-mail

我正在使用 JavaMail 1.5.2 来读取来自 IMAP 帐户的邮件.为了减少对主机的请求数量,我预取了一些消息数据,例如 From、Date、Message-ID 等:

I'm using JavaMail 1.5.2 to read messages from IMAP accounts. To reduce the number of requests to the host I prefetch some message data, like From, Date, Message-ID etc.:

Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);

FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
fp.add("Message-ID");

Message msgs[] = folder.getMessages();
folder.fetch(msgs,fp);

但是,我还想预取 一些 部分内容以创建邮件的预览文本,而无需加载包含所有附件的完整邮件.例如,我想预取所有类型为text/plain"且没有附件的内容部分.这可能吗?

However, I want to also prefetch some parts of the content to create a preview text for the mail without having to load the full message with all attachments. For example, I would like to prefetch all parts of the content that have the type "text/plain" and are no attachments. Is that possible?

PS:我不是在寻找像 fp.add(IMAPFolder.FetchProfileItem.MESSAGE) 这样的解决方案,因为这会预取带有所有附件的 整个 消息.

PS: I'm not searching for a solution like fp.add(IMAPFolder.FetchProfileItem.MESSAGE) because this will prefetch the whole message with all attachments.

推荐答案

你必须先获取bodystructure,然后遍历message structure,检查每个part的mime类型,然后下载你想要的part.IMAP 允许您使用一个命令下载所有部分,因此,如果 Javamail 有点聪明,您应该能够使用两个 IMAP 命令完成此操作,无论您最终要下载多少正文部分.

You have to retrieve the bodystructure first, then loop across the message structure, check the mime type of each part, and download the parts you want. IMAP lets you download all of the parts using one command, so if Javamail is a little smart, you should be able to do this with two IMAP commands, no matter how many bodyparts you end up wanting to download.

如果您是喜欢查看有线流量的类型,IMAP 命令应该类似于 a uid fetch 234789 bodystructure 后跟 b uid fetch 234789 (body.peek[1.1] body.peek[2]).

The IMAP commands, if you're the type who likes to look at wire traffic, should be something like a uid fetch 234789 bodystructure followed by b uid fetch 234789 (body.peek[1.1] body.peek[2]).

相关文章