使用 javamail 按域过滤电子邮件

Filter emails by domain using javamail

我正在使用 javamail 下载电子邮件,但现在我需要按域过滤一些电子邮件地址。

我尝试使用 FromStringTerm 但我不知道过滤它的正确模式。

编辑 1jmehrens 部分解决了我的问题。当我从文件夹中收到消息时,我想进行过滤,例如:

            Store store = session.getStore("imap");
            store.connect(configc.host, configc.email, configc.pass);
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);

            Message[] arrayMessages1 = folderInbox.search(??);

此时如何按域过滤?

FromStringTerm 继承了 javax.mail.search.SearchTerm:

中描述的行为

This class implements the match method for Strings. The current implementation provides only for substring matching. We could add comparisons (like strcmp ...).

所以没有模式,因为它执行开箱即用的子字符串匹配。

这是一个测试用例:

public class DomainMatch {

    public static void main(String[] args) throws Exception {
        MimeMessage msg = new MimeMessage((Session) null);
        msg.addFrom(InternetAddress.parse("foo@bar.org"));
        msg.saveChanges();

        System.out.println(new FromStringTerm("@bar.org").match(msg));
        System.out.println(new FromStringTerm("@spam.org").match(msg));
    }
}

使用 javax.mail.Folder::search 文档,您可以编写如下内容:

Store store = session.getStore("imap");
store.connect(configc.host, configc.email, configc.pass);
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);

Message[] onlyBarOrg = folderInbox.search(new FromStringTerm("@bar.org"));