ekalchev
ekalchev

Reputation: 962

Mailkit - Get HTML and Text parts without having full mime message

I want to download text and html parts from mime message and store it in the database and later if needed to download attachments. I need this because I don't want to store the attachments in my database to save disk space and bandwidth. They will be downloaded on demand later. I am not sure if I can do that and still be able to use MimeParser from MimeKit

I am planning to do that:

  1. Get message body structure and find the text and html parts
  2. Download text and html body parts using ImapFolder.GetStream and store in database preserving mime tree structure by saving section names along with headers. Attachment will not be downloaded

Later I want to show the message in the UI but I want to delay parsing until the mail message needs to be shown in the UI.

This is my progress so far

var msgSummaries = remoteFolder.Fetch(new int[] { remoteMessage.Index }, MessageSummaryItems.BodyStructure);

 var stream = remoteFolder.GetStream(remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier);

 //at this point i am saving the stream to the database and later i am trying to convert it to mime entity like that
 var parser = new MimeParser(ParserOptions.Default, stream, true);
 var mimeEntity = parser.ParseEntity(cancellationToken);

Unfortunatelly the stream doesn't contain mime part headers and cannot be parsed and I don't see an option to request headers inside GetStream method like this

FETCH 1 (BODY.PEEK[2.MIME] BODY.PEEK[2])

Any suggestions?

Upvotes: 0

Views: 3127

Answers (1)

jstedfast
jstedfast

Reputation: 38538

Well, first of all, have you tried:

var mimeEntity = remoteFolder.GetBodyPart (remoteMessage.Index, msgSummaries[0].HtmlBody);

or, if you really want to use streams:

var headerStream = remoteFolder.GetStream (remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier + ".MIME");
var contentStream = remoteFolder.GetStream (remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier);

var stream = new MemoryStream ();
headerStream.CopyTo (stream);
headerStream.Dispose ();
contentStream.CopyTo (stream);
contentStream.Dispose ();
stream.Position = 0;

//at this point i am saving the stream to the database and later i am trying to convert it to mime entity like that
var parser = new MimeParser(ParserOptions.Default, stream, true);
var mimeEntity = parser.ParseEntity(cancellationToken);

Upvotes: 1

Related Questions