How to convert MimeEntity (message/rfc822) to MimeMessage (MimeKit)

394 Views Asked by At

I have an email message that contains an envelope and I want to access the contents of the envelope as a MimeMessage to retrieve the from,to,subject,body & attachment data.

The problem is; once I retrieve the enveloped message, its of type MimeEntity and I don't seem able to convert this MimeEntity into a MimeMessage.

Is it possible to convert a MimeEntity into a MimeMessage or is it possible to get the MimeEntity's message data?

    var message = await MimeMessage.Load(@"C:\temp\MimeKitTesting\sample.eml");

    MimeEntity? envelopeMessage = message.BodyParts.FirstOrDefault(x => x.ContentType.MimeType == "message/rfc822");

    if (envelopeMessage != null)
    {
        // When debugging I can see envelopeMessage.Message property but cannot access it from code. 
    }
1

There are 1 best solutions below

0
TheLegendaryCopyCoder On

After fiddling around and reading the documentation, I see that you have to cast the MimePart to MessagePart and then you can access the Message property.

var message = await MimeMessage.Load(@"C:\temp\MimeKitTesting\sample.eml");
MimeEntity? envelopeMessage = this.Message.BodyParts.FirstOrDefault(x => x.ContentType.MimeType == "message/rfc822");
if (envelopeMessage != null && envelopeMessage is MessagePart)
{
    var rfc822 = envelopeMessage as MessagePart;
    if (rfc822 != null)
        this.Message = rfc822.Message;
}