如何使用SmtpClient.SendAsync发送带附件的电子邮件?

lab*_*lbe 31 .net asp.net email 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我目前的错误


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 ---
Run Code Online (Sandbox Code Playgroud)

    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);
    }
Run Code Online (Sandbox Code Playgroud)

lig*_*t78 37

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