.net – 如何使用SmtpClient.SendAsync发送带有附件的电子邮件?
发布时间:2020-05-25 00:33:56 所属栏目:asp.Net 来源:互联网
导读:我使用一个服务组件通过ASP.NET MVC。 我想以异步方式发送电子邮件,让用户做其他的东西,而不必等待发送。 当我发送消息没有附件它工作正常。 当我发送包含至少一个内存中附件的消息时,它会失败。 所以,我想知道是否可以使用异步方法与内存中的附件。 这里
|
我使用一个服务组件通过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得到读取之前(因为它是异步的)。在回调中销毁您的流。(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- ASP.NET:将内容注入所有Response流
- asp.net – 从互联网上打开excel文件会打开一个空
- 如果ASP.NET应用程序的CustomErrors设置为Off,有
- 使用可靠的WPF / .NET背景学习ASP.NET MVC
- asp.net – asp:ContentPlaceHolder和代码块问题
- ASP.Net Cookieless如何工作?
- 在ASP.NET Razor中格式化字符串
- asp.net-web-api – 默认请求标头不接受任何值,它
- asp.net-mvc – Resharper导航到MVC视图
- asp.net-mvc-4 – .net 4.5 ASP.Net web API JSO
热点阅读
