C#MS Exchange将电子邮件移动到文件夹

补充:感谢用户@grapkulec,我正在使用

using Microsoft.Exchange.WebServices.Data; 

我正在尝试将电子邮件移动到我已在Outlook中创建的文件夹(使用MS Exchange)。 到目前为止,我已经能够将电子邮件移动到草稿或其他众所周知的文件夹名称,但是没有成功将其移动到我创建的名为“示例”的文件夹中。

 foreach (Item email in findResults.Items) email.Move(WellKnownFolderName.Drafts); 

上面的代码有效; 但我不想使用众所周知的文件夹。 而且,如果我尝试将代码更改为:

 email.Move(Folder.(Example)); 

要么

 email.Move(Folder.["Example"]); 

它不移动(在两种情况下都会引发错误)。 我已经找到了很多关于如何将电子邮件移动到MSDN,SO和一般C#上的文件夹的示例 – 但仅限于Outlook(草稿,垃圾邮件等)“知道”的文件夹,这些文件不适用于我创建的文件夹。

解决了!

无论多次尝试,移动命令都会失败,因为ID格式不正确。 显然,移动操作不允许使用名称。 我曾尝试使用DisplayName作为标识符,这就是让我失望的原因。 最后,我放弃了DisplayName,这本来有帮助。 相反,我指向ID(通过将其存储在变量中来阻止令人讨厌的“ID格式错误”错误),并且移动工作正常。

码:

  Folder rootfolder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot); rootfolder.Load(); foreach (Folder folder in rootfolder.FindFolders(new FolderView(100))) { // Finds the emails in a certain folder, in this case the Junk Email FindItemsResults findResults = service.FindItems(WellKnownFolderName.JunkEmail, new ItemView(10)); // This IF limits what folder the program will seek if (folder.DisplayName == "Example") { // Trust me, the ID is a pain if you want to manually copy and paste it. This stores it in a variable var fid = folder.Id; Console.WriteLine(fid); foreach (Item item in findResults.Items) { // Load the email, move the email into the id. Note that MOVE needs a valid ID, which is why storing the ID in a variable works easily. item.Load(); item.Move(fid); } } } 

看来你正在使用EWS托管API,所以这里是我如何做这些事情的答案。

项目上的移动方法可以接受WellKnownFolderName或文件夹ID。 如果我理解正确,您希望将电子邮件移至名为“示例”的文件夹中。 首先,您需要获取此文件夹的文件夹对象:

 var filter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Example"); var view = new FolderView(1) { PropertySet = new PropertySet(BasePropertySet.FirstClassProperties) }; var findFoldersResults = exService.FindFolders(filter, view); folder = findFoldersResults.FirstOrDefault(f => f.DisplayName.Equals("Example", StringComparison.OrdinalIgnoreCase)); 

现在您应该拥有“Example”文件夹变量,并且可以将其id传递给电子邮件的Move方法。 有关更多详细信息,请查看有关如何使用EWS托管API的msdn页面,其中有很多简单和基本的用法示例。

BTW:WellKnownFolderNames枚举是大多数常见Exchange文件夹的便利类型,如收件箱,已发送邮件等。您还需要通过搜索/或绑定来自行检索其他任何其他Exchange对象。

基于这些答案,创建了一个移动到文件夹的工作方法,可能对某人有用:

 ///  /// Moves the email to the specified folder. ///  /// Email message to move. /// Display name of the folder. public void MoveToFolder(EmailMessage mail, string folderName) { Folder rootfolder = Folder.Bind(_exchangeService, WellKnownFolderName.MsgFolderRoot); rootfolder.Load(); Folder foundFolder = rootfolder.FindFolders(new FolderView(100)).FirstOrDefault(x => x.DisplayName == folderName); if (foundFolder == default(Folder)) { throw new DirectoryNotFoundException(string.Format("Could not find folder {0}.", folderName)); } mail.Move(foundFolder.Id); }