如何异步发送邮件
本文关键字:异步 何异步 | 更新日期: 2023-09-27 18:01:47
namespace Binarios.admin
{
public class SendEmailGeral
{
public SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
public MailMessage msg = new MailMessage();
public void Enviar(string sendFrom, string sendTo, string subject, string body)
{
string pass = "12345";
System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential(sendFrom, pass);
//setup SMTP Host Here
client.UseDefaultCredentials = false;
client.Credentials = smtpCreds;
client.EnableSsl = true;
MailAddress to = new MailAddress(sendTo);
MailAddress from = new MailAddress(sendFrom);
msg.IsBodyHtml = true;
msg.Subject = subject;
msg.Body = body;
msg.From = from;
msg.To.Add(to);
client.Send(msg);
}
}
}
我有这个代码,但我想改进它的方式,我可以异步发送邮件。你能建议任何想法,以改善这段代码或其他方式做到这一点。我尝试过visual studio建议的异步属性,但无法使用它们。
SmtpClient
允许您异步发送,并在发送完成时使用事件通知您。这可能使用起来很不方便,所以您可以创建一个扩展方法来返回Task
:
public static Task SendAsync(this SmtpClient client, MailMessage message)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Guid sendGuid = Guid.NewGuid();
SendCompletedEventHandler handler = null;
handler = (o, ea) =>
{
if (ea.UserState is Guid && ((Guid)ea.UserState) == sendGuid)
{
client.SendCompleted -= handler;
if (ea.Cancelled)
{
tcs.SetCanceled();
}
else if (ea.Error != null)
{
tcs.SetException(ea.Error);
}
else
{
tcs.SetResult(null);
}
}
};
client.SendCompleted += handler;
client.SendAsync(message, sendGuid);
return tcs.Task;
}
要获得发送任务的结果,您可以使用ContinueWith
:
Task sendTask = client.SendAsync(message);
sendTask.ContinueWith(task => {
if(task.IsFaulted) {
Exception ex = task.InnerExceptions.First();
//handle error
}
else if(task.IsCanceled) {
//handle cancellation
}
else {
//task completed successfully
}
});
大胆猜测,但SendAsync可能会完成这项工作!
从
client.Send(msg);
:
client.SendAsync(msg);
更多细节
link1
link2