我有一个任务可以从特定的电子邮件中下载/保存附件
我已经从许多网站的引用中编写了代码(包括堆栈溢出答案),但Console应用程序无法保存附件。
这是我的代码
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:\Users\u532246\Desktop", attachment.FileName);
attachment.SaveAsFile(filename);
Console.WriteLine("berhasil");
Console.ReadLine();
}
}
break;
}
MyApp = null;
}
catch (Exception ex)
{
}
也许我在这里做错了,因为我对这种任务是陌生的..
谢谢您的帮助,我真的很感激
答案 0 :(得分:0)
问题似乎是附件数组索引从 1 开始,而不是从 0 开始,正如您在发布的示例代码中所使用的那样。
所以您的 for
循环代码应该是:
for (int i = 1; i <= attachments.Count; i++)
{
Outlook.Attachment attachment = attachments[i];
string filename = Path.Combine(@"C:\Users\u532246\Desktop", attachment.FileName);
attachment.SaveAsFile(filename);
Console.WriteLine("berhasil");
Console.ReadLine();
}