我编写了一种将outlook电子邮件附件保存到硬盘并将文件转换为Base64String的方法。当我保存附件时,嵌入的(内联)图像也会被保存,即使它们不是REAL附件。我只想保存真正的附件。然后我修改了如下方法。但是现在我从“.OfType()”行得到一个错误。
这是我的代码:
private string GetBase64StringForAttachments(Outlook.MailItem mailItem)
{
StringBuilder builder = new StringBuilder();
Outlook.Attachments mailAttachments = mailItem.Attachments;
try
{
if (mailAttachments != null)
{
Regex reg = new Regex(@"<img .+?>", RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
MatchCollection matches = reg.Matches(mailItem.HTMLBody);
for (int i = 1; i <= mailAttachments.Count; i++)
{
Outlook.Attachment currentAttachment = mailAttachments[i];
bool isMatch = matches
.OfType<Match>()
.Select(m => m.Value)
.Where(s => s.IndexOf("cid:" + currentAttachment.FileName, StringComparison.InvariantCultureIgnoreCase) >= 0)
.Any();
MessageBox.Show(currentAttachment.FileName + ": " + (isMatch ? "Inline Image" : "Attached Image"));
if (currentAttachment != null)
{
string date = DateTime.Now.ToString("yyyymmddhhmmss");
string path = "C:\\test\\" + date + currentAttachment.FileName; //ToDo: Create Folder
currentAttachment.SaveAsFile(path);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] filebytes = new byte[fs.Length];
fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
builder.Append(encodedData).Append(",");
Marshal.ReleaseComObject(currentAttachment);
}
}
if (builder.Length > 0)
{
string encodedAttachments = builder.ToString().Remove(builder.ToString().Length-1);
return builder.ToString();
}
else
return "";
}
else return "";
}
catch (Exception ex)
{
Debug.DebugMessage(2, "Error in GetBase64StringForAttachments : in AddinModule " + ex.Message);
return "";
}
finally
{
Marshal.ReleaseComObject(mailAttachments);
}
}
这是错误讯息:
'System.Text.RegularExpressions.MatchCollection'不包含'OfType'的定义,也没有接受第一个类型为'System.Text.RegularExpressions.MatchCollection'的扩展方法'OfType'(你是否遗漏了) using指令或程序集引用?)
我需要什么:
我不是LINQ的忠实粉丝。那么,请你就此建议我
有更好的方法吗?
我已经尝试过按照这些问题的建议答案,但它们对我不起作用
Saving only the REAL attachments of an Outlook MailItem
Don't save embed image that contain into attachements (like signature image)
答案 0 :(得分:1)
是的,Redemption公开RDOAttachment。Hidden
属性 - 它检查HTML正文以确保附件不用作内嵌图像。
另请注意,您可以使用RDOAtttachment。AsArray
访问附件数据,而无需先将附件保存为文件。
Redemption.RDOSession rSession = new Redemption.RDOSession();
rSession.MAPIOBJECT = mailItem.Application.Session.MAPIOBJECT;
Redemption.RDOMail rMail= rSession.GetRDOFolderFromOutlookObject(mailItem)
foreach (Redemption.RDOAttachment attach in rMail.Attachments)
{
if ((attach.Type == Redemption.rdoAttachmentType.olByValue) && (!attach.Hidden))
{
attach.SaveAsFile(path);
}
}
next
答案 1 :(得分:0)
using Attachment = MsgReader.Outlook.Storage.Attachment;
foreach (Attachment attachment in mailItem.Attachments.Where(a => ((Attachment)a).Hidden == false)) {
// do whatever you want with the 'real' attachments.
}