이메일에 대한 비동기 IMAP 작업 수행 방법
ImapClient와 비동기 작업
Aspose.Email을 사용하여 메시지를 비동기적으로 작업할 수 있습니다. ImapClient. 이 문서는 메일함에서 메시지를 비동기적으로 검색하는 방법을 보여줍니다. 또한 검색 기준을 제공하여 메시지를 나열하는 방법도 보여줍니다. MailQuery. 작업 기반 비동기 패턴(TAP)으로 시작된 이메일 메시지 작업을 중단하는 방법은 별도로 표시됩니다 (TAP) 메서드.
메시지 비동기 검색
다음 코드 스니펫은 메시지를 비동기적으로 검색하는 방법을 보여줍니다.
MailQuery를 사용한 비동기 메시지 목록
다음은 MailQuery 클래스는 비동기적으로 지정된 메시지 목록을 검색하기 위한 검색 기준을 지정하는 데 사용할 수 있으며, 다음 코드 샘플에 나와 있습니다.
비동기적으로 메시지 보내기
비동기 이메일 전송은 매우 편리합니다. 프로세스가 프로그램이나 스레드의 실행을 차단하지 않기 때문에, 이메일이 전송되는 동안 다른 작업을 진행할 수 있습니다.
다음 기능들은 프로젝트에 비동기 전송을 구현하는 데 도움이 됩니다:
-
IAsyncImapClient - 애플리케이션이 인터넷 메시지 액세스 프로토콜(IMAP)을 사용해 메시지에 접근하고 조작할 수 있도록 합니다.
-
ImapClient.CreateAsync - Aspose.Email.Clients.Imap.ImapClient 클래스를 새 인스턴스로 생성합니다
아래 코드 샘플은 백그라운드에서 메시지를 나열하는 방법을 보여줍니다:
// 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()
{
}
}
비동기 작업 관리
TAP 메서드 중단
.NET Framework 4.5부터 TAP 모델에 따라 구현된 비동기 메서드를 사용할 수 있습니다. 아래 코드 스니펫은 task 기반 비동기 패턴 메서드인 AppendMessagesAsync 그리고 잠시 후 이 프로세스를 중단합니다.
// 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);
}
비동기 작업 취소
때때로 비동기 작업을 중지해야 할 상황이 발생합니다. 이를 위해 라이브러리는 CancellationToken 매개변수를 사용한 비동기 작업 취소를 제공합니다. 취소를 지원하는 비동기 메서드를 호출할 때 CancellationToken 인스턴스를 매개변수로 전달할 수 있으며, 이 토큰은 작업의 취소 신호 및 제어에 사용됩니다.
취소를 활성화하려면 먼저 CancellationToken을 제공하는 CancellationTokenSource 인스턴스를 생성해야 합니다. 그런 다음 비동기 메서드에 CancellationToken을 전달하여 실행 중에 취소 요청을 확인하도록 합니다.
다음은 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();