我使用异步方式为当前的 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)
[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/