【问题标题】:How to attach .docx and .doc files to the email from memory stream?如何将 .docx 和 .doc 文件从内存流附加到电子邮件?
【发布时间】:2019-02-08 14:55:23
【问题描述】:

我正在使用file attachmentmemory stream,因为temporary storage 不是一个选项。

在这里我做了一个Jpeg 图片附件。我查看了其他文件类型,您可以通过切换MediaTypeNames 来执行相同的操作,不幸的是.doc.docx 不在其中。

我想知道你们中是否有人知道这个特殊场合的package and how to use it

//...set up MailMessage, add a bunch of non-file content to it

MemoryStream jpgStream = new MemoryStream();
string filename = uploadedFile.FileName;

System.Drawing.Image theImage = System.Drawing.Image.FromStream(uploadedFile.InputStream);

theImage.Save(jpgStream, System.Drawing.Imaging.ImageFormat.Jpeg); 

jpgStream.Seek(0L, SeekOrigin.Begin);
emailMessage.Attachments.Add(new Attachment(jpgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg));

//something extra and send email...

【问题讨论】:

    标签: c# .net asp.net-mvc memorystream .doc


    【解决方案1】:

    您应该使用 MediaTypeNames.Application.Octet 作为 mime 类型。

    发件人:https://docs.microsoft.com/fr-fr/dotnet/api/system.net.mime.mediatypenames.application.octet?view=netframework-4.7.2

    【讨论】:

    • 如果我这样做,那么附件将无法阅读。原因是我没有将字节流编码到文件中。例如,这一行:theImage.Save(jpgStream, System.Drawing.Imaging.ImageFormat.Jpeg); 将流编码为jpeg,然后附件才变得可读。不幸的是,我不能将它用于.docx,因为它不是图像,而且这个Save() 方法来自System.Drawing.Image 命名空间。
    • Omg >_sorry to have ever doubted you :D。我之前用different image formats(比如.png,甚至是同样的.jpg)试过这个,但它没有用。现在我尝试了您所说的任何内容以防万一,它似乎与.docx 一起工作得很好,我将在.docx 文件中对更复杂的内容进行更多测试以防万一:)
    【解决方案2】:

    感谢Benoit Gidon 的回答。我再次被证明,你的假设是你最大的敌人。

    显然就这么简单,不需要任何其他特殊方法,只要将file.InputStream直接放入附件即可,不像其他S.O.帖子让你相信: https://stackoverflow.com/questions/9095880/attach-multiple-image-formats-not-just-jpg-to-email

    https://stackoverflow.com/questions/5336239/attach-a-file-from-memorystream-to-a-mailmessage-in-c-sharp

    如果有人真的在苦苦挣扎,这里是代码:

    foreach (HttpPostedFileBase file in fullViewModel.filesCollection)
                {
                    string filename = file.FileName;
    
                     msg.Attachments.Add(new Attachment(file.InputStream, filename, MediaTypeNames.Application.Octet));
                }
    

    我使用包含5000 words 内容的.docx 文档以及tablespictures 对此进行了测试,并按照我的gmail 客户端中的方式进行了重构。

    刚刚测试过,.png也一样,所以不需要PngBitmapDecoder

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      相关资源
      最近更新 更多