如何在 C# 中异步发送电子邮件获得成功或失败通知?

How to get success or failure notification Asynchronously sending Emails in C#?

我使用 Asynchronously 为我当前的 C# 项目准备了一封电子邮件通知。

smtpClient.SendMailAsync(message);

但是没有这种方法可以从该电子邮件中获取成功或失败通知。你能为此建议一个合适的方法吗? 这是下面的代码:

MailMessage mail = new MailMessage(); 
mail.From = new MailAddress("me@mycompany.com"); 
mail.To.Add("you@yourcompany.com"); 
mail.Subject = "This is an email"; 
mail.Body = "this is the body content of the email."; 
SmtpClient smtp = new SmtpClient("127.0.0.1"); //specify the mail server address 
object userState = mail; 
smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted); 
smtp.SendAsync( mail, userState ); 

如果您查看 SmtpClient.SendMailAsync 的方法签名,您会发现它 returns 是 Task。现在,如果您查看代码,您会发现任何异常都将被捕获并通过该方法公开的 Task 返回。如果您希望传播任何异常,则必须等待方法调用:

await smtpClient.SendMailAsync(message)

这就是 source code looks like:

[HostProtection(ExternalThreading = true)]
public Task SendMailAsync(MailMessage message)
{
    // Create a TaskCompletionSource to represent the operation
    var tcs = new TaskCompletionSource<object>();

    // Register a handler that will transfer completion results to the TCS Task
    SendCompletedEventHandler handler = null;
    handler = (sender, e) => HandleCompletion(tcs, e, handler);
    this.SendCompleted += handler;

    // Start the async operation.
    try { this.SendAsync(message, tcs); }
    catch
    {
        this.SendCompleted -= handler;
        throw;
    }

    // Return the task to represent the asynchronous operation
    return tcs.Task;
}

HandleCompletion

private void HandleCompletion(TaskCompletionSource<object> tcs,
                              AsyncCompletedEventArgs e,
                              SendCompletedEventHandler handler)
{
    if (e.UserState == tcs)
    {
        try { this.SendCompleted -= handler; }
        finally
        {
            if (e.Error != null) tcs.TrySetException(e.Error);
            else if (e.Cancelled) tcs.TrySetCanceled();
            else tcs.TrySetResult(null);
        }
    }
}