从 MimeMessage 获取 MimeEntity

Get MimeEntity from MimeMessage

我有一个应用程序需要解析电子邮件,这些电子邮件可能已加密也可能未加密。我有完整的流程可以很好地处理加密的电子邮件,但未加密的电子邮件给我带来了麻烦,因为我想在电子邮件被解密后使用相同的代码来完成我正在做的事情。当电子邮件未加密时,我有一个 MimeMessage,我需要以某种方式将其转换为 MimeEntity,以便它通过我为加密消息编写的解析代码。

这是我的代码示例,注意

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();
   ...

你要的是这个:

decrypted = message.Body as MimeEntity;

BodyParts 属性 是一个 IEnumerable<MimeEntity>,这就是为什么将其转换为 MimeEntity 对您不起作用。