C# MS Exchange Move Email To Folder

Kprof picture Kprof · Dec 3, 2012 · Viewed 17.9k times · Source

Added: thanks to user @grapkulec, I am using

using Microsoft.Exchange.WebServices.Data;

I am trying to move an email to a folder that I've already created in Outlook (using MS Exchange). So far, I've been able to move the email to the drafts or another well known folder name, but have had no success moving it to a folder I created called "Example."

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

The above code works; but I don't want to use the well known folders. And, if I try to change the code to something like:

email.Move(Folder.(Example));

or

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

It doesn't move (in both cases, throws an error). I've found tons of examples of how to move emails into folders on MSDN, SO and general C# - but ONLY of folders that are "well known" to Outlook (Drafts, Junk Email, etc), which doesn't work with a folder that I've created.

Answer

Kprof picture Kprof · Dec 4, 2012

Solved!

The Move command failed regardless of several attempts because the ID was malformed. Apparently a move operation doesn't allow use of names. I had tried DisplayName as an identifier and that's what kept throwing me off. Finally, I gave up on DisplayName, which would have helped. Instead I pointed to the ID (which stopped the annoying "ID is malformed" error) by storing it in a variable, and the move worked.

Code:

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<Item> 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);
        }
    }
}