'How to delete an email account ( one added in Tools->Account Settings -> Email) through C#

I tried to delete the root folder associated with an email account using Outlook Namesapce's Remove Store method but it throws an error saying it is associated to an email account. So how do I delete an email account added in Outlook from C#?

 private void RemovePersonalFoldersStore(Outlook._Application OutlookApp)
    {
        Outlook.NameSpace ns = null;
        Outlook.Folders rootFolders = null;
        Outlook.MAPIFolder folder = null;
        String acc = "";
        try
        {
            ns = OutlookApp.GetNamespace("MAPI");
            rootFolders = ns.Folders;
            foreach (Outlook.Account a in ns.Stores.Session.Accounts)
            {
                acc = a.DisplayName;
            }

            for (int i = 1; i <= rootFolders.Count; i++)
            {
                folder = rootFolders[i];
                if (folder != null)
                {
                    if (!folder.Name.Equals(OutlookApp.Session.DefaultStore.DisplayName))
                    {

                        ns.RemoveStore(folder);

                    }

                    folder = null;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {

        }
    }


Solution 1:[1]

Namespace.RemoveStore removes a PST account. If you need to delete a mail (as opposed to a store) account, you need to use IOlkAccountManager.DeleteAccount Extended MAPI method (C++ or Delphi). In case of C#, you can use Redemption (I am its author - it wraps Extended MAPI) and its RDOAccount.Delete method.

Solution 2:[2]

The Outlook object model doesn't provide any property or method for deleting mail accounts. Instead, you can use a low-level API - Extended MAPI (or any other third-party wrapper around that API). To delete an account you need to use the IOlkAccountManager::DeleteAccount method. See Using Account Management API (IOlkAccountManger) to List Outlook Email Accounts for the sample code.

You may also find the IProfAdmin::DeleteProfile method helpful which deletes a profile. If the profile to delete is in use when DeleteProfile is called, DeleteProfile returns S_OK but does not delete the profile immediately. Instead, DeleteProfile marks the profile for deletion and deletes it after it is no longer being used, when all of its active sessions have ended. See the IProfAdmin interface for more information.

You can find the sample code in the MAPI Application: How to programmatically remove Hotmail accounts from existing MAPI profiles article.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2