我正在通过ASP.NETMVC使用服务组件. 我想以异步方式发送邮箱,让用户不必等待发送就可以做其他事情.

当我发送一条没有附件的消息时,它可以正常工作.

所以,我想知道是否可以使用带有内存附件的异步方法.

以下是发送方法


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

推荐答案

不要在这里使用"using".您在调用SendAsync后立即销毁内存流,例如,可能是在SMTP读取它之前(因为它是异步的).在回调中销毁流.

Asp.net相关问答推荐

ASP.NET Core 延迟加载始终返回 null

在 Web.Config 中模拟标签

如何在没有 Select 按钮的情况下在 GridView 中实现全行 Select ?

将 Global.asax 迁移到 Startup.cs

在程序集中找不到上下文类型

ASP.NET-MVC 中的表单发布上的 FormCollection 为空

如何确定 web.config 中的编译 debug="true"

这两种方法有什么区别?

将存储过程中 Select 查询的结果返回到列表

如何在 ASP.NET 应用程序中使用 jQuery 捕获提交事件?

asp.net 中的 Eval() 有什么用

oAuth ASP.NET 成员资格提供程序

如何在 ASP.NET 站点中添加 favicon.ico

如何在 ASP.net 中使用 wkhtmltopdf.exe

对 ASP.NET 2.0 网页进行单元测试的最佳方法是什么?

如何获取程序集的最后修改日期?

Docker 中的 ASPNETCORE_ENVIRONMENT

回发后运行javascript函数

DropDownList 的 SelectedValue 与 SelectedItem.Value

如何使用 int ID 列更改 ASP.net Identity 2.0 的表名?