gpt4 book ai didi

c# - SMTP.SendAsync 无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:37 27 4
gpt4 key购买 nike

我正在尝试熟悉 smtp.SendAsync,但出于某种原因,我无法让邮件消息发送异步。

这是我试过的。

//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);

};
};
};
};
}

最佳答案

将函数的整个主体包装在来自@Lloyd 帮助的 ThreadPool.QueueUserWorkItem 中。

  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);
};

}
};
};
};
});
}

关于c# - SMTP.SendAsync 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15645688/

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