Search code examples
c#databaseattachmentmailmessage

MailMessage Attachment to byte[]


I've been searching Google/SO for the past 3 days without success and hoping someone can help or point me in the right direction.

We have a method (with a bunch to overloads) that sends emails. I'm tasked with saving the email into a database.

Question

How can I extract the contents of an attachment into a byte[] in order to save it to the database?

I've read a lot of samples that saves attachments to disk, but I want to avoid saving to disk then reading that into memory (maybe that's why I haven't found anything because it's not possible, doubt it).


Solution

  • So I think what your asking is how to convert the stream to bytes then you will not have to save it to disk. You can use this extension method to do that.

    public static class StreamExtensions
    {
        public static byte[] ReadAllBytes(this Stream instream)
        {
            if (instream is MemoryStream)
                return ((MemoryStream) instream).ToArray();
    
            using (var memoryStream = new MemoryStream())
            {
                instream.CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }
    }
    

    see https://stackoverflow.com/a/33611922/237109

    with that method you can do this

    System.Net.Mail.MailMessage m = new MailMessage();
    foreach (var element in m.Attachments)
    {
      byte[] bytes = element.ContentStream.ReadAllBytes()
       element.ContentType // you will want to save this as well so you can convert it to a file when you need to pull it back out of the database.
    }