使用 POP3 客户端进行异步电子邮件处理
Contents
[
Hide
]
使用 Pop3Client 的异步操作
使用 Aspose.Email 也可以异步处理消息 Pop3Client。本文展示了如何异步检索邮箱中的消息,并展示了如何使用 MailQuery。将另行展示如何使用基于任务的异步模式(TAP)方法。
异步检索邮件
以下代码片段展示了如何异步检索邮件。
使用 MailQuery 异步列出消息
该 MailQuery 类可用于指定检索消息列表的搜索条件,示例代码如下所示。
中断 TAP 方法
从 .NET Framework 4.5 开始,您可以使用按照 TAP 模型实现的异步方法。下面的代码片段展示了如何使用任务式异步模式(TAP)方法来接收邮箱信息,方法名为 GetMailboxInfoAsync 然后在一段时间后中断此过程。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (Pop3Client client = new Pop3Client(host, 995, senderEmail, password, SecurityOptions.Auto))
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
Exception exception = null;
ThreadPool.QueueUserWorkItem(delegate
{
try
{
// start receiving mailbox information
var task = client.GetMailboxInfoAsync(cancellationTokenSource.Token);
Pop3MailboxInfo mailboxInfo = task.GetAwaiter().GetResult();
Console.WriteLine("Message count: " + mailboxInfo.MessageCount);
}
catch (Exception e)
{
exception = e;
}
finally
{
autoResetEvent.Set();
}
});
Thread.Sleep(2000);
// stop receiving mailbox information
cancellationTokenSource.Cancel();
autoResetEvent.WaitOne();
if (exception is OperationCanceledException)
Console.WriteLine("Operation has been interrupted: " + exception.Message);
}