Filter emails by domain using javamail

梦想与她 提交于 2020-12-13 05:34:30

问题


I'm using javamail to download emails, but now I need to filter some email address by domain.

I try to use the FromStringTerm but I can't know the correct pattern to filter it.

edit 1: the jmehrens solved partially my problem. I would like to filter when i get messages from folder, something like:

            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(??);

How can I filter by domain at this point?


回答1:


The FromStringTerm inherits the behavior described in 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 ...).

So there is no pattern as it performs substring matching out of the box.

Here is a test case:

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));
    }
}

Using the javax.mail.Folder::search documentation you would write something like:

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"));


来源:https://stackoverflow.com/questions/40895033/filter-emails-by-domain-using-javamail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!