如何使用C#从Outlook电子邮件保存/下载附件



我得到一个任务,从特定电子邮件下载/保存附件

我已经从许多网站的引用中编写了代码(包括堆栈溢出答案(,但是控制台应用程序不会保存附件。

这是我的代码

try
{
Microsoft.Office.Interop.Outlook.Application MyApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace MailNS = MyApp.GetNamespace("mapi");
Microsoft.Office.Interop.Outlook.MAPIFolder MyInbox = null;
MyInbox = MailNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
Microsoft.Office.Interop.Outlook._MailItem InboxMailItem = null;
Microsoft.Office.Interop.Outlook.Items oItems = MyInbox.Items;
Microsoft.Office.Interop.Outlook.MailItem mailitem = MyApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
string Query = "[Subject] = 'Test'";
InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.Find(Query);
while(InboxMailItem != null)
{
Outlook.Attachments attachments =  InboxMailItem.Attachments;
if (attachments != null && attachments.Count > 0)
{
for (int i = 0; i <= attachments.Count; i++)
{
Outlook.Attachment attachment = attachments[i];
string filename = Path.Combine(@"C:Usersu532246Desktop", attachment.FileName);
attachment.SaveAsFile(filename);
Console.WriteLine("berhasil");
Console.ReadLine();
}
}
break;
}
MyApp = null;
}
catch (Exception ex)
{
}

也许我在这里做错了什么,因为我是这种任务的新手......

谢谢你的帮助,我真的很感激

问题似乎是附件数组索引从 1 开始而不是从 0 开始,正如您在发布的示例代码中使用的那样。

因此,for循环的代码应该是:

for (int i = 1; i <= attachments.Count; i++)
{
Outlook.Attachment attachment = attachments[i];
string filename = Path.Combine(@"C:Usersu532246Desktop", attachment.FileName);
attachment.SaveAsFile(filename);
Console.WriteLine("berhasil");
Console.ReadLine();
}

最新更新