加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 19:06:54 所属栏目: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得到读取之前(因为它是异步的)。在回调中销毁您的流。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读