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

标签 c# email smtp

我使用异步方式为当前的 C# 项目准备了电子邮件通知。

smtpClient.SendMailAsync(message);

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

MailMessage mail = new MailMessage(); 
mail.From = new MailAddress("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74191134190d171b1904151a0d5a171b19" rel="noreferrer noopener nofollow">[email protected]</a>"); 
mail.To.Add("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aed7c1dbeed7c1dbdccdc1c3decfc0d780cdc1c3" rel="noreferrer noopener nofollow">[email protected]</a>"); 
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 的方法签名,您会发现它返回一个 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);
        }
    }
}

关于c# - 如何在 C# 中异步发送电子邮件获得成功或失败通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014218/

相关文章:

c# - 看看 Regex 对象是用什么模式创建的?

c# - 使用反射从 Property.GetValue 返回对象列表

c# - 在解析 XDocument 时处理空 XElement

c# - 'AsyncEnumerableReader' 在枚举值时达到了配置的最大缓冲区大小

javascript - 如何从 JavaScript 发送电子邮件

java - 解析电子邮件中签名部分的图像

PHP : send mail in localhost

java - 如何从黑莓应用程序发送 smtp 电子邮件

javascript - 如何在我的 Node.js 脚本中从我的 Gmail 帐户发送电子邮件?

java群发邮件发件人