TheLegendaryCopyCoder
TheLegendaryCopyCoder

Reputation: 1842

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

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

Upvotes: 0

Views: 693

Answers (1)

TheLegendaryCopyCoder
TheLegendaryCopyCoder

Reputation: 1842

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;
}

Upvotes: 1

Related Questions