Search code examples
c#exchange-servercategoriesexchangewebservicesblueprism

How can I prevent existing categories from disappearing when I add a new category to an email item using Exchange Web Services in C#?


I am trying to add a new category to an email item using Exchange WEB Services but when I run the code, existing categories disappear and the category I added becomes the only category. For example an email has categories X and Y and after I add my category Z to this mail item, X and Y disappears and only category for the mail becomes Z Any help is much appreciated. Thanks in advance

Please note that I am running this code inside a software called Blue Prism a low code no code scripting software and it is near impossible to implement third party libraries etc due to corporate chain of approvals and stuff

When I do it manually on the outlook 2019 it works the way I intended Here is the method I am using The DLL That uses this code is Microsoft.Exchange.WebServices.dll

//Here I initialize exchange object and authenticate
ExchangeService exchange = null;

void ConnectEWS(string ewsURL, string _exchangeVersion, string username, string password)
{
    ServicePointManager.ServerCertificateValidationCallback = delegate {return true;} ;
    try
    {
        exchange                = new ExchangeService();
        exchange.Url            = new Uri(ewsURL);
        exchange.Credentials    = new WebCredentials(username,password);
    }
    catch (Exception ex)
    {
        throw new Exception("failed to initialize exchange object!!="+ex.Message);
    }   
}
//here is my void method that adds a new category to an email item
void addCategoryToMail(string msgid, string category)
{
    if(exchange==null)
    {
        throw new Exception("exchange object is null!!");
    }   
    EmailMessage message = EmailMessage.Bind(exchange,msgid, BasePropertySet.IdOnly );
    if(message.Categories.Contains(category)==false)
    {
        message.Categories.Add(category);
        //message.Update(ConflictResolutionMode.AlwaysOverwrite);
        message.Update(ConflictResolutionMode.AutoResolve);
    }
}

Solution

  • The line

    EmailMessage message = EmailMessage.Bind(exchange,msgid, BasePropertySet.IdOnly );
    

    only requests the message id. You need to request categories. See if BasePropertySet.FirstClassProperties brings categories in. If not, explicitly request categories.