Jak*_*ake 2 c# outlook outlook-addin
我正在开发一个 Outlook 加载项,它可以以两种方式之一工作,具体取决于用户的选择 - 它可以处理选定的电子邮件,或者处理选定文件夹中的所有电子邮件。我已经让第一部分工作了,但第二部分给我带来了麻烦,可能是因为我只是错误地调整了第一部分的代码。我相信问题归根结底是在 C# Outlook 加载项中正确获取当前选定的文件夹。顺便说一句,我正在使用 .NET 3.5 和 Outlook 2007。
首先,电子邮件代码 - 如果用户在收件箱中选择一封或多封电子邮件,并使用“选定的电子邮件”选项运行我的加载项,则会运行以下代码(并且工作正常!):
public static void processSelectedEmails(Outlook.Explorer explorer)
{
//Run through every selected email
for (int i = 1; i <= explorer.Selection.Count; i++)
//alternatively, foreach (Object selectedObject in explorer.Selection)
{
Object selectedObject = explorer.Selection[i];
if (!(selectedObject is Outlook.Folder))
{
string errorMessage = "At least one of the items you have selected is not an email.";
//Code for displaying the error
return;
}
else
Outlook.MailItem email = (selectedObject as Outlook.MailItem);
//Do something with current email
}
}
Run Code Online (Sandbox Code Playgroud)
如果用户转到 Outlook 中的导航窗格(默认情况下位于左侧),选择文件夹或子文件夹(可能是收件箱、已发送邮件或他们创建的其他文件夹),我尝试调整此代码以执行其他操作。然后,用户可以在我的加载项中选择“处理所选文件夹”选项,该选项基本上与上面的代码执行相同的操作,但处理所选文件夹内的所有电子邮件。我已将其设置为仅在用户选择单个文件夹时才起作用。
public static void processFolder(Outlook.Explorer explorer)
{
//Assuming they have selected only one item
if (explorer.Selection.Count == 1)
{
//Make sure that that selected item is a folder
Object selectedObject = explorer.Selection[1];
if (!(selectedObject is Outlook.Folder))
{
string errorMessage = "The item you have selected is not a folder.";
//Code for displaying the error
return;
}
//Code for running through every email in that folder
}
}
Run Code Online (Sandbox Code Playgroud)
我还没有编写代码来实际运行所选文件夹中的所有电子邮件,因为我的代码从未通过if (!(selectedObject is Outlook.Folder)). 即使最近选择的项目是您的收件箱,我也会收到当时编写的错误。也许我误用了 explorer.Selection 的东西?任何帮助将非常感激。
这对于回答我的问题可能很重要 - 加载项有一个名为“explorer”的字段,它是在启动时生成的:explorer = this.Application.ActiveExplorer。这是传递给我的函数的“资源管理器”,以便它们可以知道选择了什么。正如我所说,这适用于选定的电子邮件,但不适用于选定的文件夹。任何见解将不胜感激!
编辑1:看来这个问题基本上是从特定文件夹获取outlook中的所有邮件的重复,但它没有答案。
编辑2:我一直在做进一步的研究,看来我可以通过创建一个弹出窗口来使用该方法选择文件夹来获得几乎相同的功能(但不幸的是需要额外的步骤)Application.Session.PickFolder()。有没有办法根据当前选择的文件夹来执行此操作,而不是强制用户选择新文件夹?
编辑3:我修改了此处找到的代码:http://msdn.microsoft.com/en-us/library/ms268994 (v=vs.80).aspx,以进一步显示哪些内容对我来说无法正常工作:
public static void processFolder(Outlook.Explorer explorer)
{
string message;
if (explorer.Selection.Count > 0)
{
Object selObject = explorer.Selection[1];
if (selObject is Outlook.MailItem)
{
message = "The item is an e-mail";
}
else if (selObject is Outlook.Folder)
{
message = "The item is a folder";
}
else
{
message = "No idea what the item is!";
}
Console.WriteLine(Message);
return;
}
}
Run Code Online (Sandbox Code Playgroud)
无论我选择邮件,还是转到导航窗格并选择文件夹,我都会收到消息“此项目是电子邮件”。
Explorer.SelectionItems仅适用于( MailItem、AppointmentItem 等)- 不适用于Folders。要访问当前选择的内容,Folder您需要Explorer.CurrentFolder.
Folder.Items将为您提供对给Items定Folder.