[英]How to save / download attachments from outlook emails with C#
我收到了从特定电子邮件下载/保存附件的任务
我已经从许多网站的参考文献中编写了代码(包括堆栈溢出答案),但控制台应用程序不会保存附件。
这是我的代码
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)
{
}
也许我在这里做错了什么,因为我对这种任务不熟悉..
谢谢你的帮助,我真的很感激
问题似乎是附件数组索引从 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.