Working with Pop3Client Asynchronously
Contents
[
Hide
]
Working with Pop3Client Asynchronously
Messages can be retrieved from mailboxes asynchronously as well by using the Aspose.Email Pop3Client. This article shows how to retrieve messages from a mailbox asynchronously. It also shows how to list messages by providing search criteria using MailQuery.
Retrieving Messages Asynchronously
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Pop3Client client = new Pop3Client();
client.setHost("pop.gmail.com");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.SSLImplicit);
client.setUsername("username");
client.setPassword("password");
try {
Pop3MessageInfoCollection messages = client.listMessages();
System.out.println("Total Number of Messages in inbox:" + messages.size());
IAsyncResult asyncResult = client.beginFetchMessage(messages.get_Item(0).getSequenceNumber());
MailMessage message = client.endFetchMessage(asyncResult);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
List Messages Asynchronously with MailQuery
The MailQuery class can be used to specify search criteria for retrieving a list of messages asynchronously as is shown in the following code sample.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailQueryBuilder builder = new MailQueryBuilder();
builder.getSubject().contains("Subject");
MailQuery query = builder.getQuery();
IAsyncResult asyncResult = client.beginListMessages(query);
Pop3MessageInfoCollection messages = client.endListMessages(asyncResult);
Cancel an Asynchronous Operation
An operation started with any of the beginXxx methods can be interrupted with the cancelAsyncOperation method inherited from EmailClient. Pass it the IAsyncResult returned when the operation was started:
try (Pop3Client client = new Pop3Client("host", 995, "username", "password", SecurityOptions.SSLImplicit)) {
IAsyncResult asyncResult = client.beginListMessages();
// Let the operation run for a while, then interrupt it
Thread.sleep(2000);
client.cancelAsyncOperation(asyncResult);
System.out.println("Operation has been interrupted.");
}
The task-based asynchronous pattern (TAP) of Aspose.Email for .NET — the
*Async methods and the CancellationToken parameter — has no counterpart in Aspose.Email for Java. Use the beginXxx / endXxx pair together with cancelAsyncOperation as shown above.