Cách thực hiện các thao tác IMAP bất đồng bộ trên Email

Các thao tác bất đồng bộ với ImapClient

Làm việc với tin nhắn có thể được thực hiện bất đồng bộ bằng cách sử dụng Aspose.Email ImapClient. Bài viết này trình bày việc truy xuất tin nhắn từ hộp thư một cách bất đồng bộ. Bài viết này cũng chỉ cách liệt kê tin nhắn bằng cách cung cấp tiêu chí tìm kiếm sử dụng MailQuery. Sẽ được trình bày riêng cách ngắt một thao tác với các tin nhắn email được bắt đầu bằng mô hình bất đồng bộ dựa trên nhiệm vụ (TAP) phương thức.

Truy xuất Tin nhắn bất đồng bộ

Đoạn mã sau cho bạn thấy cách truy xuất tin nhắn một cách bất đồng bộ.

Liệt kê Tin nhắn Bất đồng bộ với MailQuery

Cái MailQuery lớp có thể được sử dụng để chỉ định tiêu chí tìm kiếm nhằm truy xuất danh sách tin nhắn xác định một cách bất đồng bộ như được hiển thị trong mẫu mã sau.

Gửi tin nhắn bất đồng bộ

Gửi email bất đồng bộ rất tiện lợi, vì quá trình này không chặn việc thực thi của chương trình hoặc luồng. Thay vì chờ email được gửi trước khi tiếp tục các tác vụ khác, chương trình có thể tiếp tục chạy trong khi email đang được gửi ở nền.

Các tính năng sau sẽ giúp bạn triển khai việc gửi bất đồng bộ vào dự án của mình:

  • IAsyncImapClient - Cho phép các ứng dụng truy cập và thao tác các tin nhắn bằng giao thức Internet Message Access Protocol (IMAP).

  • ImapClient.CreateAsync - Tạo một thể hiện mới của lớp Aspose.Email.Clients.Imap.ImapClient

Đoạn mã mẫu dưới đây minh họa cách liệt kê tin nhắn trong nền:

// Authenticate the client to obtain necessary permissions
static readonly string tenantId = "YOU_TENANT_ID";
static readonly string clientId = "YOU_CLIENT_ID";
static readonly string redirectUri = "http://localhost";
static readonly string username = "username";
static readonly string[] scopes = { "https://outlook.office.com/IMAP.AccessAsUser.All" };

// Use the ImapAsync method for asynchronous operations
static async Task Main(string[] args)
{
    await ImapAsync();
    Console.ReadLine();
}

// Establish the connection with the server
// Create an instance of the ImapClient asynchronously using the CreateAsync method
// Select the Inbox folder using SelectFolderAsync method to complete and fetch the list of email messages asynchronously using the ListMessagesAsync method.
static async Task ImapAsync()
{
    var tokenProvider = new TokenProvider(clientId, tenantId, redirectUri, scopes);
    var client = ImapClient.CreateAsync("outlook.office365.com", username, tokenProvider, 993).GetAwaiter().GetResult();
    await client.SelectFolderAsync(ImapFolderInfo.InBox);
    var messages = await client.ListMessagesAsync();
    Console.WriteLine("Messages :" + messages.Count);
}

// Token provider implementation
public class TokenProvider : IAsyncTokenProvider
{
    private readonly PublicClientApplicationOptions _pcaOptions;
    private readonly string[] _scopes;

    public TokenProvider(string clientId, string tenantId, string redirectUri, string[] scopes)
    {
        _pcaOptions = new PublicClientApplicationOptions
        {
            ClientId = clientId,
            TenantId = tenantId,
            RedirectUri = redirectUri
        };

        _scopes = scopes;
    }

    public async Task<OAuthToken> GetAccessTokenAsync(bool ignoreExistingToken = false, CancellationToken cancellationToken = default)
    {

        var pca = PublicClientApplicationBuilder
            .CreateWithApplicationOptions(_pcaOptions).Build();

        try
        {
            var result = await pca.AcquireTokenInteractive(_scopes)
                .WithUseEmbeddedWebView(false)
                .ExecuteAsync(cancellationToken);

            return new OAuthToken(result.AccessToken);
        }
        catch (MsalException ex)
        {
            Console.WriteLine($"Error acquiring access token: {ex}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex}");
        }

        return null;
    }

    public void Dispose()
    {

    }
}

Quản lý các thao tác bất đồng bộ

Ngắt một phương thức TAP

Bắt đầu từ .NET Framework 4.5, bạn có thể sử dụng các phương thức bất đồng bộ được triển khai theo mô hình TAP. Đoạn mã dưới đây cho thấy cách thêm nhiều tin nhắn bằng phương pháp bất đồng bộ dựa trên nhiệm vụ có tên AppendMessagesAsync và sau đó ngắt quá trình này sau một thời gian.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET

List<MailMessage> mailMessages = new List<MailMessage>();

// create mail messages
for (int i = 0; i < 100; i++)
    mailMessages.Add(new MailMessage(senderEmail, receiverEmail, $"Message #{i}", "Text"));

using (ImapClient client = new ImapClient(host, 993, senderEmail, password, SecurityOptions.SSLImplicit))
{
    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
    AutoResetEvent autoResetEvent = new AutoResetEvent(false);
    Exception exception = null;

    ThreadPool.QueueUserWorkItem(delegate
    {
        try
        {
            // start uploading the messages
            var task = client.AppendMessagesAsync(mailMessages, cancellationTokenSource.Token);
            AppendMessagesResult appendMessagesResult = task.GetAwaiter().GetResult();
            Console.WriteLine("All messages have been appended.");
        }
        catch (Exception e)
        {
            exception = e;
        }
        finally
        {
            autoResetEvent.Set();
        }
    });

    Thread.Sleep(5000);

    // stop uploading the messages
    cancellationTokenSource.Cancel();
    autoResetEvent.WaitOne();

    foreach (MailMessage mailMessage in mailMessages)
        mailMessage.Dispose();

    if (exception is OperationCanceledException)
        Console.WriteLine("Operation has been interrupted: " + exception.Message);
}

Hủy các thao tác bất đồng bộ

Đôi khi bạn có thể gặp nhu cầu dừng các thao tác bất đồng bộ. Vì mục đích này, thư viện của chúng tôi cung cấp khả năng hủy các thao tác bất đồng bộ thông qua tham số CancellationToken. Khi gọi một phương thức bất đồng bộ hỗ trợ hủy, bạn có thể truyền một thể hiện CancellationToken làm tham số. CancellationToken được sử dụng để báo hiệu và kiểm soát việc hủy thao tác.

Để bật hủy, trước tiên bạn cần tạo một thể hiện CancellationTokenSource cung cấp CancellationToken. Sau đó, truyền CancellationToken vào phương thức bất đồng bộ, cho phép nó kiểm tra yêu cầu hủy trong quá trình thực thi.

Dưới đây là một ví dụ minh họa việc hủy bằng CancellationToken:

CancellationTokenSource tokenSource = new CancellationTokenSource();
AppendMessagesResult appendMessagesResult = null;
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(delegate(object state)
    {
        try
        {
            appendMessagesResult = imapClient.AppendMessagesAsync(mmList, tokenSource.Token).GetAwaiter().GetResult();
        }
        catch (Exception ex)
        {

        }
        finally
        {
            autoResetEvent.Set();
        }
    });

tokenSource.Cancel();
autoResetEvent.WaitOne();