SMTP.SendAsync不能正常工作
本文关键字:工作 常工作 SendAsync 不能 SMTP | 更新日期: 2023-09-27 18:05:55
我正在努力熟悉smtp。SendAsync,由于某种原因,我无法获得发送Async的邮件消息。
这是我试过的。
//smtp.SendAsync(mm, null)); Error, Async operation was attempted before another one completed
//Task.Run(() => smtp.SendAsync(mm, null)); No error and no email
//smtp.SendMailAsync(mm));Error, Async operation was attempted before another one completed
// Task.Run(() => smtp.SendMailAsync(mm)); No error and no email.
//smtp.Send(mm); The only one that works, but has that delay and that is what I am attempting to get away from.
我代码:public static void Email(IElevation elevation, string fromEmail, string toEmail)
{
using (Bitmap printCanvas = ShopDrawing.Merger.MergeElevationAndDoor(elevation, RotateFlipType.Rotate90FlipNone))
{
using (var ms = new MemoryStream())
{
printCanvas.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
using (MailMessage mm = new MailMessage(new MailAddress(fromEmail), new MailAddress(toEmail)))
{
mm.Subject = "[Project: " + elevation.ProjectName + "] " + " Shop drawings for " + elevation.Name;
mm.Body = "Your shop drawings are attached to this email in reference to Project: " + elevation.ProjectName + " -> Elevation: " + elevation.Name;
Attachment at = new Attachment(ms, elevation.Name + ".png", "image/png");
mm.Attachments.Add(at);
using (SmtpClient smtp = new SmtpClient())
{
//smtp.SendAsync(mm, null));
//Task.Run(() => smtp.SendAsync(mm, null));
//smtp.SendMailAsync(mm));
// Task.Run(() => smtp.SendMailAsync(mm));
//The only one that works
smtp.Send(mm);
};
};
};
};
}
将整个函数体包装在ThreadPool中。QueueUserWorkItem from @Lloyd help.
public static void EmailShopDrawingAndDoorSchedule(IElevation elevation, string fromEmail, string toEmail)
{
ThreadPool.QueueUserWorkItem(t =>
{
using (Bitmap printCanvas = ShopDrawing.Merger.MergeElevationAndDoor(elevation, RotateFlipType.Rotate90FlipNone))
{
using (var ms = new MemoryStream())
{
printCanvas.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
using (MailMessage mm = new MailMessage(new MailAddress(fromEmail), new MailAddress(toEmail)))
{
mm.Subject = "[Project: " + elevation.ProjectName + "] " + " Shop drawings for " + elevation.Name;
mm.Body = "Your shop drawings are attached to this email in reference to Project: " + elevation.ProjectName + " -> Elevation: " + elevation.Name;
using (Attachment at = new Attachment(ms, elevation.Name + ".png", "image/png"))
{
mm.Attachments.Add(at);
using (var smtp = new SmtpClient())
{
smtp.Send(mm);
};
}
};
};
};
});
}