gpt4 book ai didi

c# - 从 Outlook 获取附件

转载 作者:行者123 更新时间:2023-12-04 00:46:53 25 4
gpt4 key购买 nike

我是 2 C# 新手,我接到了一项任务...我必须编写 C# 代码以将发送的电子邮件附件和电子邮件主题从 Outlook 2007 下载到本地驱动器或任何指定位置。我怎么做?我能够获取收件箱中的附件。谁能帮我获取通过 Outlook 发送的邮件?

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.NewMail += new
Microsoft.Office.Interop.Outlook.
ApplicationEvents_11_NewMailEventHandler(ThisApplication_NewMail);
}

private void ThisApplication_NewMail()
{
Outlook.MAPIFolder SentMail = this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
Outlook.Items SentMailItems = SentMail.Items;
Outlook.MailItem newEmail = null;
//SentMailItems = SentMailItems.Restrict("[Unread] = true");
try
{
foreach (object collectionItem in SentMailItems)
{
newEmail = collectionItem as Outlook.MailItem;
if (newEmail != null)
{
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile(@"C:\TestFileSave\" + newEmail.Attachments[i].FileName);
}
}
}
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message
.Substring(0, 11);
if (errorInfo == "Cannot save")
{
MessageBox.Show(@"Create Folder C:\TestFileSave");
}
}
}

提前致谢

最佳答案

我已经测试了你的代码,Attachment 类实例的 SaveAsFile() 方法抛出:

{System.IO.DirectoryNotFoundException: Cannot save the attachment. Path does not exist. Verify the path is correct. at Microsoft.Office.Interop.Outlook.Attachment.SaveAsFile(String Path) ... }

因此,需要确保保存附件的目录存在。

private void ThisApplication_NewMail()
{
const string destinationDirectory = @"C:\TestFileSave";

if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}

MAPIFolder sentMail = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
Items sentMailItems = sentMail.Items;
try
{
foreach (object collectionItem in sentMailItems)
{
MailItem newEmail = collectionItem as MailItem;
if (newEmail == null) continue;

if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail.Attachments.Count; i++)
{
string filePath = Path.Combine(destinationDirectory, newEmail.Attachments[i].FileName);
newEmail.Attachments[i].SaveAsFile(filePath);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}

希望这对您有所帮助。

关于c# - 从 Outlook 获取附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9339146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com