Liudvikas Taluntis
Liudvikas Taluntis

Reputation: 37

How to attach .docx and .doc files to the email from memory stream?

I'm doing the file attachment through memory stream because temporary storage is not an option.

Here I did a Jpeg image attachment. I looked at other file types with which you could do the same by switching the MediaTypeNames, and unfortunately .doc and .docx is not among them.

I was wondering whether any of you know of any package and how to use it for this particular occasion?

//...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...

Upvotes: 0

Views: 1820

Answers (2)

Liudvikas Taluntis
Liudvikas Taluntis

Reputation: 37

Thanks Benoit Gidon for his answer. I was proved once again that your assumptions are your worst enemy.

Apparently it's as simple as that and you don't need any other special methods as long as you put the file.InputStream in directly into attachment, unlike other S.O. posts make you believe: 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

In case anyone is actually struggling with it, here is the code:

foreach (HttpPostedFileBase file in fullViewModel.filesCollection)
            {
                string filename = file.FileName;

                 msg.Attachments.Add(new Attachment(file.InputStream, filename, MediaTypeNames.Application.Octet));
            }

I tested this with a .docx document that had 5000 words of content in it, as well as tables and pictures, and it gets reconstructed the way it was in my gmail client.

Just tested that, it also works the same way with .png, so no need for PngBitmapDecoder.

Upvotes: 0

Benoit Gidon
Benoit Gidon

Reputation: 79

You should use MediaTypeNames.Application.Octet as mime type.

From : https://learn.microsoft.com/fr-fr/dotnet/api/system.net.mime.mediatypenames.application.octet?view=netframework-4.7.2

Upvotes: 0

Related Questions