简体   繁体   中英

Get MimeEntity from MimeMessage

I have an application that needs to parse emails, which may be encrypted or not. I have the complete flow working fine for emails that are encrypted, but the ones that are not encrypted are giving me trouble as I would like to use the same code once the email has been decrypted for what I am doing. When the email was not encrypted I have a MimeMessage, I need to cast this into a MimeEntity somehow for it to go through the parsing code that I have written for the encrypted messages.

Here is a sample of my code, notice

var pkcs7 = message.BodyParts.OfType<ApplicationPkcs7Mime>().FirstOrDefault();
MimeEntity decrypted;
if (pkcs7 != null)
{
    decrypted = decryptAndValidateEmail(pkcs7, certLocation, certPassword);
}
else
{
    //********************//
    //THIS is the code that is not working at this point

    decrypted = message.BodyParts as MimeEntity; 

    //********************//
}

var decryptedParts = new List<MimePart>();
if (decrypted is Multipart)
{
    decryptedParts = breakMultiPart((Multipart)decrypted);
}
else if (decrypted is MimePart)
{
    decryptedParts.Add((MimePart)decrypted);
}
else
{
    throw new InvalidOperationException("Unknown Mime part found");
}


var textParts = decryptedParts.Where(r => r is TextPart);
var htmlParts = textParts.Where(x => ((TextPart)x).IsHtml);
var textBodyParts = textParts.Where(x => !((TextPart)x).IsHtml);
var attachmentParts = decryptedParts.Where(r => !(r is TextPart));

if (htmlParts.Any())
{
    if (htmlParts.Count() > 1)
    {
        throw new InvalidOperationException("multiple html body parts.");
    }
    var htmlPart = (TextPart)htmlParts.First();
   ...

What you want is this:

decrypted = message.Body as MimeEntity;

The BodyParts property is an IEnumerable<MimeEntity> which is why casting it to a MimeEntity wasn't working for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM