Dot-Net
如何使用 SmtpClient.SendAsync 發送帶有附件的電子郵件?
我正在通過 ASP.NET MVC 使用服務組件。我想以非同步方式發送電子郵件,讓使用者無需等待發送就可以做其他事情。
當我發送沒有附件的消息時,它工作正常。當我發送帶有至少一個記憶體附件的消息時,它會失敗。
所以,我想知道是否可以使用帶有記憶體附件的非同步方法。
這是發送方法
public static void Send() { MailMessage message = new MailMessage("from@foo.com", "too@foo.com"); using (MemoryStream stream = new MemoryStream(new byte[64000])) { Attachment attachment = new Attachment(stream, "my attachment"); message.Attachments.Add(attachment); message.Body = "This is an async test."; SmtpClient smtp = new SmtpClient("localhost"); smtp.Credentials = new NetworkCredential("foo", "bar"); smtp.SendAsync(message, null); } }這是我目前的錯誤
System.Net.Mail.SmtpException: Failure sending mail. ---> System.NotSupportedException: Stream does not support reading. at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result) --- End of inner exception stack trace ---解決方案
public static void Send() { MailMessage message = new MailMessage("from@foo.com", "to@foo.com"); MemoryStream stream = new MemoryStream(new byte[64000]); Attachment attachment = new Attachment(stream, "my attachment"); message.Attachments.Add(attachment); message.Body = "This is an async test."; SmtpClient smtp = new SmtpClient("localhost"); //smtp.Credentials = new NetworkCredential("login", "password"); smtp.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (e.Error != null) { System.Diagnostics.Trace.TraceError(e.Error.ToString()); } MailMessage userMessage = e.UserState as MailMessage; if (userMessage != null) { userMessage.Dispose(); } }; smtp.SendAsync(message, message); }
不要在這裡使用“使用”。您在呼叫 SendAsync 後立即銷毀記憶體流,例如可能在 SMTP 讀取它之前(因為它是非同步的)。在回調中銷毀您的流。