4

I'm building a simple .net MailKit IMAP client. Rather then pulling emails again and again from the IMAP server, is it possible to store the entire MailKit mime message (in full, including attachments) as a byte array? If so, how?

Then I could write it to MySql or a file and reuse it for testing code changes.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
penCsharpener
  • 409
  • 7
  • 15

1 Answers1

11

As Lucas points out, you can use the MimeMessage.WriteTo() method to write the message to either a file name or to a stream (such as a MemoryStream).

If you want the message as a byte array in order to save it to an SQL database, you could do this:

using (var memory = new MemoryStream ()) {
    message.WriteTo (memory);

    var blob = memory.ToArray ();
    // now save the blob to the database
}

To read it back from the database, you'd first read the blob as a byte[] and then do this:

using (var memory = new MemoryStream (blob, false)) {
    message = MimeMessage.Load (memory);
}
jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • I know this is a very old thread, but I'm using this in a project and am having an issue. Writing to a memory stream fails with "cannot access a closed stream", but only when the MimeMessage contains another email as an attachment. When images or pdfs are attached, the process runs fine. Any ideas as to what could be causing this? – TheDoc May 31 '19 at 15:51
  • You are closing the stream used by the email attachment. – jstedfast May 31 '19 at 15:54