如何使用 NetOffice.Outlook C# 库区分电子邮件正文中的图像和电子邮件附加的图像?
更新:
这是我的半工作示例:
var saveInlineImages = false;
foreach (var attachment in mailItem.Attachments)
{
if (attachment == null) continue;
using (attachment)
{
var attName = attachment.FileName;
var savePath = GetSavePath();
try
{
if (!saveInlineImages && IsImage(attName) && IsInlineImage(attachment))
continue;
attachment.SaveAsFile(savePath);
}
catch
{
throw new Exception($"Failed to write the file: {savePath}");
}
}
}
private bool IsImage(string attName)
{
var lowerName = attName.ToLower();
return lowerName.EndsWith(".jpg") || lowerName.EndsWith(".jpeg") ||
lowerName.EndsWith(".png") || lowerName.EndsWith(".gif") ||
lowerName.EndsWith(".tiff") || lowerName.EndsWith(".svg") ||
lowerName.EndsWith(".raw") || lowerName.EndsWith(".ico") ||
lowerName.EndsWith(".heic");
}
private bool IsInlineImage(Attachment attachment)
{
try
{
var propertyAccessor = attachment.PropertyAccessor;
var cid = propertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F");
return !string.IsNullOrEmpty(cid?.ToString());
}
catch
{
return false;
}
}
问题是“IsInlineImage”在除 Exchange 之外的所有帐户上都能正常工作。在 Exchange 帐户中,此方法将所有邮件定义为“内联”。有没有其他通用的工作方法来检测消息正文中的图片?
无论您是否使用NetOffice,您都可以通过检查
src
属性来区分邮件正文中使用的图像。如果嵌入图像,您可以看到以下结构:
<img src="cid:image.png"/>
其中
cid:
表示所提到的图像代表附件并在邮件正文中用作图像。
您可以尝试使用
PR_ATTACH_CONTENT_ID
对象获取附加文件上的 PropertyAccessor
属性值(DASL 名称为“http://schemas.microsoft.com/mapi/proptag/0x3712001F”)。该值用于 HTML 标记中的 cid
属性。 PropertyAccessor.GetProperty 方法可以帮助完成此类任务。