gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:43:54 25 4
gpt4 key购买 nike

我使用 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 的方法签名,您会发现它返回一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com