在 POP3 服务器上检测新电子邮件
Contents
[
Hide
]
使用 POP3 帐户时,您可以在下载和阅读邮件时将其保留在服务器上。将邮件保留在服务器上意味着它们可供其他应用程序和用户访问,例如通过多台设备访问邮件的用户。或者您只想下载符合特定条件的邮件,例如具有特定主题行的邮件。要管理邮件,您可以:
- 使用 Aspose.Email 读取 POP3 邮件服务器上的所有消息。
- 将消息下载到本地数据库。
这些消息不会被删除,而是保留在服务器上。第一次运行时,过程正常,所有所需的消息都会下载到数据库。但第二次运行时,由于这些消息仍留在邮件服务器上,会再次下载相同的消息,从而导致重复记录。为解决此问题,请使用 Pop3MessageInfo.UniqueID 属性用于检查消息是否已下载。必须将消息的唯一 ID 存储在数据库中:它是检测新消息的搜索键。
检测新消息
从 POP3 服务器上的邮件列表中识别新邮件:
- 连接到服务器。
- 获取邮件列表。
- 连接到数据库。
- 获取邮件列表。
- 比较列表。
- 将新邮件保存到数据库。
当您执行以下操作时,流程更快:
- 将所有消息的唯一 ID 获取到哈希表中。
- 在 for(…) 循环中,为每封电子邮件在哈希表中搜索,而不是在数据库中搜索。
此方法仅需一次调用,而无需为每条消息查询数据库,从而避免大量数据库请求。以下代码片段演示了如何在 POP3 服务器上检测新电子邮件。
public static void run() {
try {
// Connect to the POP3 mail server and check messages.
Pop3Client pop3Client = new Pop3Client("pop.domain.com", 993, "username", "password");
// List all the messages
Pop3MessageInfoCollection msgList = pop3Client.listMessages();
for (Pop3MessageInfo msgInfo : msgList) {
// Get the POP3 message's unique ID
String strUniqueID = msgInfo.getUniqueId();
// Search your local database or data store on the unique ID. If a match is found, that means it's already downloaded. Otherwise download and save it.
if (searchPop3MsgInLocalDB(strUniqueID) == true) {
// The message is already in the database. Nothing to do with this message. Go to next message.
} else {
// Save the message
savePop3MsgInLocalDB(msgInfo);
}
}
} catch (Exception ex) {
System.err.println(ex);
}
}
private static void savePop3MsgInLocalDB(Pop3MessageInfo msgInfo) {
// Open the database connection according to your database. Use public properties (for example msgInfo.Subject) and store in database,
// for example, " INSERT INTO POP3Mails (UniqueID, Subject) VALUES ('" + msgInfo.UniqueID + "' , '" + msgInfo.Subject + "') and Run the query to store in database.
}
private static boolean searchPop3MsgInLocalDB(String strUniqueID) {
// Open the database connection according to your database. Use strUniqueID in the search query to find existing records,
// for example, " SELECT COUNT(*) FROM POP3Mails WHERE UniqueID = '" + strUniqueID + "' Run the query, return true if count == 1. Return false if count == 0.
return false;
}