Search code examples
c#emailexchangewebserviceseml

C# Unable to Bind EmailMessage


I have a method which converts Email to .eml format.

However, the statement of EmailMessage.Bind suddenly stops working without any error.

Below is my code snippet:

public static string convertEmailToEml(EmailMessage emailMessage, string caseNumber, string EMLSaveFilePath)
{
    Console.WriteLine(emailMessage.Subject); //correct value
    Console.WriteLine(caseNumber); //correct value
    Console.WriteLine(EMLSaveFilePath); //correct value
    Console.WriteLine(emailMessage.Id); //correct value


    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
    PropertySet props = new PropertySet(EmailMessageSchema.MimeContent);

    var email = EmailMessage.Bind(service, emailMessage.Id, props); //not executed
    string emlFullPath = EMLSaveFilePath + caseNumber + ".eml"; //not executed

    Console.WriteLine(emlFullPath); //code not reached
    Console.ReadKey();

    using (FileStream fs = new FileStream(emlFullPath, FileMode.Create, FileAccess.Write))
    {
        fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
    }
    return emlFullPath;
}

May I know if there are any places that I can look into?

There were warning messages upon solution building as follows, not sure if they are linked:

Found conflicts between different versions of the same dependent assembly that could not be resolved. These reference conflicts are listed in the build log when log verbosity is set to detailed.

Exception Thrown during Debug Mode:

'Microsoft.Exchange.WebServices.Data.ServiceLocalException' in Microsoft.Exchange.WebServices.dll("The Url property of the ExchangeService object must be set.")

I have verified that service, emailMessage.Id, and props values are not null.


Solution

  • Based on the documentation for `EmailMessage.Bind(...), it states that this method results in a call to Exchange Web Services (EWS).

    You create an instance of ExchangeService but you do not provide a URL to it (documentation). This is a requirement. The exception that is thrown is pointing you directly at the missing data.