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建议但不能使用它们的异步属性。
答案 0 :(得分:11)
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
}
});
答案 1 :(得分:1)
狂野猜测,但SendAsync可能会完成这项工作!
答案 2 :(得分:0)