处理来自服务器的消息
获取邮箱信息
我们可以使用以下方式获取邮箱信息,例如邮件数量和邮箱大小。 getMailBoxSize 和 getMailBoxInfo 的 方法 Pop3Client 类。
- 该 getMailBoxSize 方法返回邮箱的字节大小。
- 该 getMailBoxInfo 方法返回一个类型为 Pop3MailBoxInfo.
也可以使用以下方式获取邮件数量 MessageCount 属性以及使用 OccupiedSize 属性的 Pop3MailBoxInfo 类。下面的示例代码展示了如何获取邮箱信息。它展示了如何:
- 创建一个 Pop3Client.
- 连接到 POP3 服务器。
- 获取邮箱大小。
- 获取邮箱信息。
- 获取邮箱中的邮件数量。
- 获取已占用的大小。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
// Get the size of the mailbox, Get mailbox info, number of messages in the mailbox
long nSize = client.getMailboxSize();
System.out.println("Mailbox size is " + nSize + " bytes.");
Pop3MailboxInfo info = client.getMailboxInfo();
int nMessageCount = info.getMessageCount();
System.out.println("Number of messages in mailbox are " + nMessageCount);
long nOccupiedSize = info.getOccupiedSize();
System.out.println("Occupied size is " + nOccupiedSize);
获取邮箱中的邮件计数
下面的代码片段展示了如何统计邮箱中的电子邮件数量。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Pop3Client client = new Pop3Client("pop3.server.com", "username", "password");
try {
client.setSecurityOptions(SecurityOptions.Auto);
int i = client.getMessageCount();
System.out.println("Message count: " + i);
} catch (Pop3Exception ex) {
System.out.println("Error:" + ex.toString());
}
Aspose.Email 让开发者以多种方式处理电子邮件。例如,他们可以在决定是否下载邮件之前检索标题信息。或者他们可以从服务器检索电子邮件并直接保存(更快),或在解析后保存(更慢)。本文展示了如何检索和转换电子邮件。
检索电子邮件标题信息
电子邮件标题可以提供关于邮件的信息,以决定是否检索整封邮件。通常,标题信息包含发件人、主题、接收日期等。(电子邮件标题的详细说明请参见 自定义电子邮件标题。该主题专门讨论使用 SMTP 发送电子邮件,但电子邮件标题内容信息仍适用于 POP3 邮件)。以下示例展示如何通过邮件序列号从 POP3 服务器检索电子邮件标题。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username. password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
try {
HeaderCollection headers = client.getMessageHeaders(1);
for (int i = 0; i < headers.size(); i++) {
// Display key and value in the header collection
System.out.print(headers.getKey(i));
System.out.print(" : ");
System.out.println(headers.get(i));
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
client.dispose();
}
检索电子邮件
该 Pop3Client 类组件提供从 POP3 服务器检索电子邮件并将其解析为 MailMessage 在…的帮助下的实例 MailMessage 组件。该 MailMessage 类包含多个属性和方法用于操作电子邮件内容。通过使用 fetchMessage 方法的 Pop3Client 类,您可以获取一个 MailMessage 实例直接从 POP3 服务器获取。以下代码片段展示了如何从 POP3 服务器检索完整的电子邮件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
try {
int messageCount = client.getMessageCount();
// Create an instance of the MailMessage class and Retrieve message
MailMessage message;
for (int i = 1; i <= messageCount; i++) {
message = client.fetchMessage(i);
System.out.println("From:" + message.getFrom());
System.out.println("Subject:" + message.getSubject());
System.out.println(message.getHtmlBody());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
client.dispose();
}
使用唯一 ID 检索消息摘要信息
API 的 POP3 客户端可以使用邮件的唯一 ID 从服务器检索消息摘要信息。这使得无需先检索完整邮件即可快速访问邮件的简要信息。以下代码片段展示了如何检索消息摘要信息。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String uniqueId = "unique id of a message from server";
Pop3Client client = new Pop3Client("host.domain.com", 456, "username", "password");
client.setSecurityOptions(SecurityOptions.Auto);
Pop3MessageInfo messageInfo = client.getMessageInfo(uniqueId);
if (messageInfo != null) {
System.out.println(messageInfo.getSubject());
System.out.println(messageInfo.getDate());
}
使用多连接列出消息
Pop3Client 提供了一个 UseMultiConnection 属性可用于在繁重操作时创建多个连接。您也可以通过使用 Pop3Client.ConnectionsQuantity。以下代码片段演示了使用多连接模式列出消息,并将其性能与单连接模式进行比较。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the Pop3Client class
Pop3Client pop3Client = new Pop3Client();
pop3Client.setHost("<HOST>");
pop3Client.setPort(995);
pop3Client.setUsername("<USERNAME>");
pop3Client.setPassword("<PASSWORD>");
pop3Client.setConnectionsQuantity(5);
pop3Client.setUseMultiConnection(MultiConnectionMode.Enable);
long multiConnectionModeStartTime = System.currentTimeMillis();
Pop3MessageInfoCollection messageInfoCol1 = pop3Client.listMessages();
long multiConnectionModeTimeSpan = System.currentTimeMillis() - multiConnectionModeStartTime;
pop3Client.setUseMultiConnection(MultiConnectionMode.Disable);
long singleConnectionModeStartTime = System.currentTimeMillis();
Pop3MessageInfoCollection messageInfoCol2 = pop3Client.listMessages();
long singleConnectionModeTimeSpan = System.currentTimeMillis() - singleConnectionModeStartTime;
System.out.println("multyConnectionModeTimeSpan: " + multiConnectionModeTimeSpan);
System.out.println("singleConnectionModeTimeSpan: " + singleConnectionModeTimeSpan);
double performanceRelation = singleConnectionModeTimeSpan / multiConnectionModeTimeSpan;
System.out.println("Performance Relation: " + performanceRelation);
从服务器获取邮件并保存到磁盘
保存邮件到磁盘(不解析)
如果想从 POP3 服务器下载邮件而不解析它们,请使用 Pop3Client 类 saveMessage 函数。 saveMessage 函数不解析邮件,因此比 fetchMessage 函数。下面的代码片段展示了如何按序列号(此处为 1)保存邮件。 saveMessage 方法将邮件以原始 EML 格式保存而不进行解析。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "pop3/";
String dstEmail = dataDir + "InsertHeaders.eml";
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
try {
// Save message to disk by message sequence number
client.saveMessage(1, dstEmail);
client.dispose();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("Retrieved email messages using POP3 ");
保存前解析消息
下面的代码片段使用了 Pop3Client fetchMessage 根据序列号从 POP3 服务器检索邮件,然后使用主题作为文件名保存到磁盘的方法。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "pop3/";
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username and password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
try {
// Fetch the message by its sequence number and Save the message using its subject as the file name
MailMessage msg = client.fetchMessage(1);
msg.save(dataDir + "first-message_out.eml", SaveOptions.getDefaultEml());
client.dispose();
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
client.dispose();
}
批量获取邮件
Pop3Client 提供了一个 fetchMessages 接受序列号或唯一标识的可迭代对象并返回列表的方法 MailMessage。下面的代码片段演示了 fetchMessages 根据序列号和唯一标识获取邮件的方法。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the Pop3Client class
Pop3Client pop3Client = new Pop3Client();
pop3Client.setHost("<HOST>");
pop3Client.setPort(995);
pop3Client.setUsername("<USERNAME>");
pop3Client.setPassword("<PASSWORD>");
Pop3MessageInfoCollection messageInfoCol = pop3Client.listMessages();
System.out.println("ListMessages Count: " + messageInfoCol.size());
List<Integer> sequenceNumberAr = new ArrayList<Integer>();
List<String> uniqueIdAr = new ArrayList<String>();
for (Pop3MessageInfo mi : messageInfoCol) {
sequenceNumberAr.add(mi.getSequenceNumber());
uniqueIdAr.add(mi.getUniqueId());
}
for (MailMessage m : pop3Client.fetchMessagesBySequences(sequenceNumberAr)) {
System.out.println("FetchMessages-sequenceNumberAr : " + m.getSubject());
}
for (MailMessage m : pop3Client.fetchMessagesByUids(uniqueIdAr)) {
System.out.println("FetchMessages-uniqueIdAr : " + m.getSubject());
}
按发送者、收件人或日期过滤消息
该 Pop3Client 类,详见 连接到 POP3 服务器,提供 listMessages 方法获取邮箱中的所有邮件。若只获取符合某些条件的邮件,请使用重载的 listMessages 方法接受 MailQuery 作为参数。 MailQuery 类提供了多种属性用于指定查询条件,例如日期、主题、发件人、收件人等。 MailQueryBuilder 类用于构建搜索表达式。首先设置所有条件和约束,然后 MailQuery 被填充为由 … 开发的查询 MailQueryBuilder。该 MailQuery 类对象被用于 Pop3Client 从服务器提取过滤后的信息。本文展示了如何从邮箱过滤电子邮件。第一个示例说明了如何根据日期和主题过滤消息。我们还展示了如何对其他条件进行过滤以及如何构建更复杂的查询。还展示了日期和时间过滤器的应用,以检索特定的电子邮件。此外,还展示了如何应用区分大小写的过滤。
从邮箱过滤消息
过滤邮箱中的消息:
- 连接并登录 POP3 服务器.
- 创建以下实例: MailQuery 并设置所需的属性。
- 调用 Pop3Client.listMessages(MailQuery query) 方法并传递 MailQuery 作为参数仅获取过滤后的邮件。
下面的代码片段展示了如何连接到 POP3 邮箱并获取今天到达且主题中包含 “newsletter” 的邮件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Connect and log in to POP3
String host = "host";
int port = 110;
String username = "user@host.com";
String password = "password";
Pop3Client client = new Pop3Client(host, port, username, password);
// Set conditions, Subject contains "Newsletter", Emails that arrived today
MailQueryBuilder builder = new MailQueryBuilder();
builder.getSubject().contains("Newsletter");
builder.getInternalDate().on(new Date());
// Build the query and Get list of messages
MailQuery query = builder.getQuery();
Pop3MessageInfoCollection messages = client.listMessages(query);
System.out.println("Pop3: " + messages.size() + " message(s) found.");
获取满足特定条件的消息
上述代码示例 根据电子邮件主题和日期过滤消息。我们也可以使用其他属性设置其他支持的条件。以下是使用…设置条件的一些示例 MailQuery.
以下代码片段展示了如何根据其他条件过滤电子邮件:
- 查找今天发送的电子邮件。
- 查找在特定范围内接收的电子邮件。
- 查找来自特定发送者的电子邮件。
- 查找来自特定域的电子邮件。
- 查找发送给特定收件人的电子邮件。
今天的日期
下面的代码片段展示了如何查找今天发送的电子邮件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Emails that arrived today
MailQueryBuilder builder = new MailQueryBuilder();
builder.getInternalDate().on(new Date());
日期范围
下面的代码片段展示了如何查找在特定时间范围内收到的电子邮件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Emails that arrived in last 7 days
Calendar calendar = Calendar.getInstance();
builder.getInternalDate().before(calendar.getTime());
calendar.add(Calendar.DATE, -7);
builder.getInternalDate().since(calendar.getTime());
特定发送者
下面的代码片段展示了如何查找来自特定发送者的电子邮件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Get emails from specific sender
builder.getFrom().contains("saqib.razzaq@127.0.0.1");
特定域
下面的代码片段展示了如何查找来自特定域的电子邮件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Get emails from specific domain
builder.getFrom().contains("SpecificHost.com");
特定收件人
下面的代码片段展示了如何查找发送给特定收件人的电子邮件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Get emails sent to specific recipient
builder.getTo().contains("recipient");
构建复杂查询
如果不同 MailQueryBuilder 属性在独立的语句中设置时,所有条件都会被匹配。例如,如果我们想获取特定日期范围内且来自特定主机的邮件,需要编写三条语句。
使用 AND 组合查询
下面的代码片段展示了如何使用 AND 组合查询。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Emails from specific host, get all emails that arrived before today and all emails that arrived since 7 days ago
builder.getFrom().contains("SpecificHost.com");
Calendar calendar = Calendar.getInstance();
builder.getInternalDate().before(calendar.getTime());
calendar.add(Calendar.DATE, -7);
builder.getInternalDate().since(calendar.getTime());
使用 OR 组合查询
MailQueryBuilder 提供了 或 接受两个 MailQuery 实例作为参数。它获取匹配任意一个指定条件的消息。下面的代码片段展示了如何过滤主题中包含 “test” 或发件人为 “noreply@host.com” 的消息。下面的代码片段展示了如何使用 OR 组合查询。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Specify OR condition
builder.or(builder.getSubject().contains("test"), builder.getFrom().contains("noreply@host.com"));
应用区分大小写的过滤器
API 还提供基于区分大小写的条件过滤邮箱电子邮件的功能。以下方法提供了使用区分大小写标志搜索电子邮件的能力。
- Method StringComparisonField.contains(String value, boolean ignoreCase)
- Method StringComparisonField.equals(String value, boolean ignoreCase)
- Method StringComparisonField.notContains(String boolean, bool ignoreCase)
- Method StringComparisonField.notEquals(String boolean, bool ignoreCase)
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// IgnoreCase is True
MailQueryBuilder builder1 = new MailQueryBuilder();
builder1.getFrom().contains("tesT", true);
MailQuery query1 = builder1.getQuery();
Pop3MessageInfoCollection messageInfoCol1 = client.listMessages(query1);