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

前端之家收集整理的这篇文章主要介绍了.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得到读取之前(因为它是异步的)。在回调中销毁您的流。

猜你在找的asp.Net相关文章