以编程方式将多个文件附加到电子邮件而不写入磁盘

发布于 2024-08-19 11:58:47 字数 3500 浏览 2 评论 0原文

我们的项目将文件作为 blob 存储在 SQL Server 数据库中。我想从数据库中获取文件并将多个文件附加到电子邮件中而不写入磁盘。

这就是我到目前为止所拥有的(一切正常,没有附件):

// snip

List<System.Net.Mail.Attachment> attachments = null;
// Attachments is a child list of Messagebody object holding Attachment ids
MessageBody.Attachments = MessageBodyAttachmentList.GetMessageBodyAttachmentList(this.MessageBody.ID);

if (MessageBody.Attachments != null && MessageBody.Attachments.Count > 0)
{
    attachments = new List<Attachment>();

    foreach (Library.Entity.Messaging.MessageBodyAttachment att in MessageBody.Attachments)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            // create a new attachment
            Library.Attachments.Attachment attachment = Library.Attachments.Attachment.GetAttachment(att.AttachmentID);

            byte[] contentAsBytes = attachment.FileData;// FileData holds byte[] that is the contents of the file
            memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length);
            memoryStream.Seek(0, SeekOrigin.Begin);

            // content type for file info
            ContentType contentType = new ContentType();
            contentType.MediaType = MediaTypeNames.Application.Octet;
            contentType.Name = attachment.FileName;

            // create the .Net specific attachment
            Attachment netAttachment = new Attachment(memoryStream, contentType);
            attachments.Add(netAttachment);

            memoryStream.Position = 0;
        }
    }
}

response = message.SendMessage(_recipient, _sender, _cc, _bcc, MessageBody.Subject, MessageBody.Body, true, attachments);
// snip

public string SendMessage(string to, string from, string cc, string bcc, string subject, string body, bool IsHtml,  List<Attachment> attachments)
{
    string response = String.Empty;
    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to, subject, body);

    // Add the attachments
    if (attachments != null)
    {
        foreach (Attachment a in attachments)
            message.Attachments.Add(a);
    }

    message.IsBodyHtml = IsHtml;

    if (IsHtml)
    {
        // snip
    }

    try
    {
        _client.Timeout = 500000;
        _client.Send(message);
    }
    catch (SmtpException smtpex)
    {
        response = smtpex.Message;
    }
    catch (System.Exception ex)
    {
        response = ex.Message;
    }
    return response;
}

我收到以下错误:

exception message: Failure sending mail.
source: System
stack trace:
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at MyCompany.Shared.Email.SMTPMessage.SendMessage(String to, String from, String cc, String bcc, String subject, String body, Boolean IsHtml, List`1 attachments) in C:\svn_repos\branches\2010.02.28\Net\Common\Shared\Email\SMTPMessage.cs:line 116

inner exception msg: Cannot access a closed Stream.
inner source: mscorlib
inner targetsite: {Void StreamIsClosed()}
inner stack trace:
   at System.IO.__Error.StreamIsClosed()
   at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Mime.MimePart.Send(BaseWriter writer)
   at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
   at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope)
   at System.Net.Mail.MailMessage.Send(BaseWriter writer, Boolean sendEnvelope)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)

我从网上找到的示例复制了大部分流代码。

Our project has files stored in a sql server db as blobs. I'd like to get the files from the database and attach multiple files to an email without writing to disk.

This is what I have so far(everything works ok, with no attachments):

// snip

List<System.Net.Mail.Attachment> attachments = null;
// Attachments is a child list of Messagebody object holding Attachment ids
MessageBody.Attachments = MessageBodyAttachmentList.GetMessageBodyAttachmentList(this.MessageBody.ID);

if (MessageBody.Attachments != null && MessageBody.Attachments.Count > 0)
{
    attachments = new List<Attachment>();

    foreach (Library.Entity.Messaging.MessageBodyAttachment att in MessageBody.Attachments)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            // create a new attachment
            Library.Attachments.Attachment attachment = Library.Attachments.Attachment.GetAttachment(att.AttachmentID);

            byte[] contentAsBytes = attachment.FileData;// FileData holds byte[] that is the contents of the file
            memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length);
            memoryStream.Seek(0, SeekOrigin.Begin);

            // content type for file info
            ContentType contentType = new ContentType();
            contentType.MediaType = MediaTypeNames.Application.Octet;
            contentType.Name = attachment.FileName;

            // create the .Net specific attachment
            Attachment netAttachment = new Attachment(memoryStream, contentType);
            attachments.Add(netAttachment);

            memoryStream.Position = 0;
        }
    }
}

response = message.SendMessage(_recipient, _sender, _cc, _bcc, MessageBody.Subject, MessageBody.Body, true, attachments);
// snip

public string SendMessage(string to, string from, string cc, string bcc, string subject, string body, bool IsHtml,  List<Attachment> attachments)
{
    string response = String.Empty;
    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to, subject, body);

    // Add the attachments
    if (attachments != null)
    {
        foreach (Attachment a in attachments)
            message.Attachments.Add(a);
    }

    message.IsBodyHtml = IsHtml;

    if (IsHtml)
    {
        // snip
    }

    try
    {
        _client.Timeout = 500000;
        _client.Send(message);
    }
    catch (SmtpException smtpex)
    {
        response = smtpex.Message;
    }
    catch (System.Exception ex)
    {
        response = ex.Message;
    }
    return response;
}

I'm getting the following errors:

exception message: Failure sending mail.
source: System
stack trace:
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at MyCompany.Shared.Email.SMTPMessage.SendMessage(String to, String from, String cc, String bcc, String subject, String body, Boolean IsHtml, List`1 attachments) in C:\svn_repos\branches\2010.02.28\Net\Common\Shared\Email\SMTPMessage.cs:line 116

inner exception msg: Cannot access a closed Stream.
inner source: mscorlib
inner targetsite: {Void StreamIsClosed()}
inner stack trace:
   at System.IO.__Error.StreamIsClosed()
   at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Mime.MimePart.Send(BaseWriter writer)
   at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
   at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope)
   at System.Net.Mail.MailMessage.Send(BaseWriter writer, Boolean sendEnvelope)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)

I copied most of the stream code from examples I found on the web.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情释 2024-08-26 11:58:47

您已经找到了不实现 using 块的原因:当块退出后您仍要使用该对象时。将 MemoryStreamusing 块中取出。

You've found a reason to not implement a using block: when you're still going to use the object after the block has exited. Take the MemoryStream out of the using block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文