JavaMail-如何搜索电子邮件

JavaMail-如何搜索电子邮件

撰写  
最后更新于2019年7月9日|   打印  电子邮件
JavaMail API使开发人员可以编写代码来搜索用户收件箱中的电子邮件。这可以通过调用Folder提供search()函数来完成。类:

 

Message []搜索(SearchTerm词)

 

此方法返回一个Message对象数组,这些对象与SearchTerm的子类指定的搜索条件匹配我们需要创建一个从SearchTerm扩展并覆盖其方法match()的类例如:

1个
2
3
4
5
6
7
8
9
10
11
12
SearchTerm term = new SearchTerm() {
    public boolean match(Message message) {
        try {
            if (message.getSubject().contains("Java")) {
                return true;
            }
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }
};
 

如我们所见,如果带有主题包含单词“ Java”的消息,上面match()方法返回true。换句话说,上面的搜索词将匹配在其“主题”字段中具有单词“ Java”的所有消息。并将此新SearchTerm对象传递给搜索方法,如下所示:

1个
Message[] foundMessages = folder.search(term);
 

搜索()如果没有找到匹配方法返回一个空数组。Folder类的类为相应的协议(即IMAPFolder类和POP3Folder类)实现此搜索功能

以下程序通过IMAP协议连接到邮件服务器,并在收件箱文件夹内的“主题”字段中搜索所有包含单词“ JavaMail”的消息。这是代码:

1个
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18岁
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65岁
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package net.codejava.mail;
 
import java.util.Properties;
 
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.SearchTerm;
 
/**
 * This program demonstrates how to search for e-mail messages which satisfy
 * a search criterion.
 * @author www.codejava.net
 *
 */
public class EmailSearcher {
 
    /**
     * Searches for e-mail messages containing the specified keyword in
     * Subject field.
     * @param host
     * @param port
     * @param userName
     * @param password
     * @param keyword
     */
    public void searchEmail(String host, String port, String userName,
            String password, final String keyword) {
        Properties properties = new Properties();
 
        // server setting
        properties.put("mail.imap.host", host);
        properties.put("mail.imap.port", port);
 
        // SSL setting
        properties.setProperty("mail.imap.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.imap.socketFactory.fallback", "false");
        properties.setProperty("mail.imap.socketFactory.port",
                String.valueOf(port));
 
        Session session = Session.getDefaultInstance(properties);
 
        try {
            // connects to the message store
            Store store = session.getStore("imap");
            store.connect(userName, password);
 
            // opens the inbox folder
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);
 
            // creates a search criterion
            SearchTerm searchCondition = new SearchTerm() {
                @Override
                public boolean match(Message message) {
                    try {
                        if (message.getSubject().contains(keyword)) {
                            return true;
                        }
                    } catch (MessagingException ex) {
                        ex.printStackTrace();
                    }
                    return false;
                }
            };
 
            // performs search through the folder
            Message[] foundMessages = folderInbox.search(searchCondition);
 
            for (int i = 0; i < foundMessages.length; i++) {
                Message message = foundMessages[i];
                String subject = message.getSubject();
                System.out.println("Found message #" + i + ": " + subject);
            }
 
            // disconnect
            folderInbox.close(false);
            store.close();
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider.");
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store.");
            ex.printStackTrace();
        }
    }
 
    /**
     * Test this program with a Gmail's account
     */
    public static void main(String[] args) {
        String host = "imap.gmail.com";
        String port = "993";
        String userName = "your_email";
        String password = "your_password";
        EmailSearcher searcher = new EmailSearcher();
        String keyword = "JavaMail";
        searcher.searchEmail(host, port, userName, password, keyword);
    }
 
}
 

我们可以结合使用Message对象的多个属性来创建更复杂的搜索条件,例如:

1个
2
3
4
if (message.getSubject().contains(keyword)
        && message.getSentDate().after(aDate)) {
    return true;
}
 

以下是一些有用的搜索条件:

“从”字段的搜索条件:

1个
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18岁
19
20
21
22
23
24
25
26
27
28
29
30
31
package net.codejava.mail;
 
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.SearchTerm;
 
public class FromFieldSearchTerm extends SearchTerm {
    private String fromEmail;
     
    public FromFieldSearchTerm(String fromEmail) {
        this.fromEmail = fromEmail;
    }
     
    @Override
    public boolean match(Message message) {
        try {
            Address[] fromAddress = message.getFrom();
            if (fromAddress != null && fromAddress.length > 0) {
                if (fromAddress[0].toString().contains(fromEmail)) {
                    return true;
                }
            }
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
         
        return false;
    }
     
}
 

发送日期字段的搜索条件:

1个
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18岁
19
20
21
22
23
24
25
26
27
28
package net.codejava.mail;
 
import java.util.Date;
 
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.SearchTerm;
 
public class SentDateSearchTerm extends SearchTerm {
    private Date afterDate;
     
    public SentDateSearchTerm(Date afterDate) {
        this.afterDate = afterDate;
    }
     
    @Override
    public boolean match(Message message) {
        try {
            if (message.getSentDate().after(afterDate)) {
                return true;
            }
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }
 
}
 

邮件内容的搜索条件:

1个
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18岁
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package net.codejava.mail;
 
import java.io.IOException;
 
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.SearchTerm;
 
public class ContentSearchTerm extends SearchTerm {
    private String content;
     
    public ContentSearchTerm(String content) {
        this.content = content;
    }
     
    @Override
    public boolean match(Message message) {
        try {
            String contentType = message.getContentType().toLowerCase();
            if (contentType.contains("text/plain")
                    || contentType.contains("text/html")) {
                String messageContent = message.getContent().toString();
                if (messageContent.contains(content)) {
                    return true;
                }
            }
        } catch (MessagingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;
    }
 
}
 

笔记:

您需要使用JavaMail jar文件。如果使用Maven,则将以下依赖项添加到  pom.xml  文件中:

1个
2
3
4
5
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>
这会将  javax.mail-VERSION.jar  和  Activation-VERSION.jar添加 到项目的类路径中。如果您必须手动添加它们,请从JavaMail Project页面下载 

 

其他JavaMail教程:


关于作者:

是经过认证的Java程序员(SCJP和SCWCD)。他在Java 1.4时代开始使用Java编程,从那时起就爱上了Java。 Facebook上与他交朋友

附件:
EmailSearcher.java [用于搜索电子邮件的示例程序] 2 kB

添加评论

剩下500个符号

后续评论通知我

进行人机身份验证
reCAPTCHA

评论 

1 2 3
#14 mohana 2019-05-24 02:59
String subject = message.getSubject(); getting different subject ( Delivery Status Notification (Failure)) for the kickback back mail from Mail Delivery System
can any one help me how to read original mail subject for kick back mails from Mail Delivery System.
Quote
#13Sailendra Narayan Je2018-12-12 02:47
Quoting Surendra Nath Jena:
[quote name="Nam"]Hi Sailendra Narayan Je,

So there is probably no results matching your condition. What do you search for?


Yes i unable to search mail using this code.
Quote
#12devendra patil2017-04-08 07:52
It is taking time to show the messages
Quote
#11devendra2017-03-31 02:36
sir,
please will you make a video on this gmail search code, it will help me out.
Quote
#10 周杰伦2016-02-07 23:16
Java邮件,用于按主题或其他条件搜索邮件
引用
1 2 3


Tags: published
November 01, 2019 at 01:59PM
Open in Evernote

评论

此博客中的热门博文

使用静态Aria2二进制文件快速安装Aria2,及使用方法 - Rat's Blog

Oldghost's Blog » 群晖(Synology)反向代理服务器教程

使用Holer远程登录家里或公司内网的电脑 – Rat’s Blog