public XElement GetEmailByExchangeId(string messageId)
        {
            try
            {
                if (string.IsNullOrEmpty(messageId))
                {
                    throw new Exception("L'id exchange ne peut pas être null.");
                }
                crmService = new XrmServices();
                Entity email = Activity.GetEmail(messageId, crmService);

                if (email != null && email.Id != Guid.Empty)
                {
                    var queue = Activity.GetActivityQueue(email.Id, crmService);
                    result.AddResultElement("activityid", email.Id.ToString());
                    if (queue == null)
                    {
                        throw new Exception("Le mail n'est pas attribué à une file d'attente.");
                    }
                    int status = email.GetAttributeValue <OptionSetValue>("new_status").Value;
                    //Si le mail est au statut <à traiter> ou <rejeté>.
                    if (status == 100000000 || status == 100000002)
                    {
                        //S'il est différent de crm-admin c'est qu'un concierge traite déjà ce mail.
                        if (email.GetAttributeValue <EntityReference>("ownerid").Id != crmService.callerId.Id)
                        {
                            returnCode = (int)CustomReturnCode.MailInProgress;
                        }
                        else
                        {
                            //Entity queue = Activity.GetActivityQueue(email.Id, crmService);
                            if (queue.GetAttributeValue <EntityReference>("new_contractid") != null && queue.GetAttributeValue <EntityReference>("new_contractid").Id != Guid.Empty)
                            {
                                Guid contractId = queue.GetAttributeValue <EntityReference>("new_contractid").Id;
                                switch (queue.GetAttributeValue <OptionSetValue>("new_type").Value)
                                {
                                    #region Email

                                case 100000000:
                                    //var attachment = Activity.GetEmailAttachement(email.Id, crmService);


                                    /*var sender =
                                     *  email.GetAttributeValue<EntityCollection>("from")
                                     *      .Entities.FirstOrDefault(
                                     *          e =>
                                     *              e.GetAttributeValue<EntityReference>("partyid")
                                     *                  .LogicalName.ToLower() == "contact");*/

                                    EntityCollection froms = email.GetAttributeValue <EntityCollection>("from");

                                    // MK
                                    Entity sender = null;
                                    if ((froms.Entities.Count > 0) && froms.Entities[0].Contains("partyid") && (froms.Entities[0].GetAttributeValue <EntityReference>("partyid") != null) && (froms.Entities[0].GetAttributeValue <EntityReference>("partyid").LogicalName.ToLower() == "contact"))
                                    {
                                        sender = froms.Entities[0];
                                    }

                                    if (sender != null && sender.Id != Guid.Empty)
                                    {
                                        List <Entity> contactList =
                                            Contact.GetContactByEmailOnContract(
                                                contractId,
                                                sender.GetAttributeValue <string>("addressused"),
                                                crmService);

                                        CheckRequest(contactList, email, crmService, "email");
                                    }

                                    else
                                    {
                                        returnCode = (int)CustomReturnCode.CustomerNotFound;
                                    }
                                    break;

                                    #endregion

                                    #region Fax

                                case 100000001:


                                    var regResult = Regex.Match(email.GetAttributeValue <string>("subject").Replace(" ", ""),
                                                                @"(\+\d{2,3}.?\d{9}?)", RegexOptions.IgnorePatternWhitespace);

                                    if (regResult.Groups.Count > 0)
                                    {
                                        string faxNumber = regResult.ToString();
                                        //Mail de type FAX
                                        email.Attributes.Add("new_type", new OptionSetValue(100000005));
                                        var customerList = Contact.GetContactByPhoneOnContract(contractId,
                                                                                               faxNumber, crmService);
                                        CheckRequest(customerList, email, crmService, "fax");
                                    }
                                    else
                                    {
                                        returnCode = (int)CustomReturnCode.CustomerNotFound;
                                    }


                                    break;

                                    #endregion

                                default:
                                    throw new Exception("L'email ne répond pas aux critères de traitement.");
                                    break;
                                }
                            }
                            else
                            {
                                #region SmartPhone / SMS

                                #region Traitement Smartphone
                                Entity updateEmail = new Entity("email");
                                updateEmail.Id = email.Id;
                                if (queue.GetAttributeValue <string>("name").ToLower().Contains("smartphone"))
                                {
                                    //Charge le xml du mail pour créer la demande.
                                    var xml =
                                        Activity.GetEmailAttachement(
                                            email.GetAttributeValue <string>("description"), queue.GetAttributeValue <string>("name").ToLower()).Root.Elements().FirstOrDefault();
                                    XNamespace RootNamespace = xml.GetDefaultNamespace();
                                    XNamespace requestNs     =
                                        xml.Element(RootNamespace + "request").GetNamespaceOfPrefix("a");
                                    var    request  = xml.Element(RootNamespace + "request");
                                    Entity customer =
                                        Contact.GetContactById(xml.Element(RootNamespace + "userid").Value,
                                                               crmService);

                                    updateEmail.Attributes.Add("new_customeridentification", xml.Element(RootNamespace + "userid").Value);
                                    updateEmail.Attributes.Add("new_type", new OptionSetValue(100000003));
                                    if (customer.Id != Guid.Empty)
                                    {
                                        Entity newIncident = new Entity("incident")
                                        {
                                            Attributes = new AttributeCollection()
                                            {
                                                new KeyValuePair <string, object>("customerid", customer.ToEntityReference()),
                                                new KeyValuePair <string, object>("new_callerphonenumber",
                                                                                  request.Element(requestNs + "phone").Value)
                                                //new KeyValuePair<string, object>("customerid", customer.Id)
                                            }
                                        };
                                        try
                                        {
                                            newIncident.Id = crmService.GetService().Create(newIncident);
                                            result.AddResultElement("demandeid", newIncident.Id);
                                            if (newIncident.Id != Guid.Empty)
                                            {
                                                //email.Attributes.Remove("regardingobjectid");
                                                updateEmail.Attributes.Add("regardingobjectid", newIncident.ToEntityReference());
                                                string commentaire =
                                                    request.Element(requestNs + "text").Value;
                                                string typeCode =
                                                    request.Element(requestNs + "typecode").Value;
                                                string customerEmail =
                                                    request.Element(requestNs + "email").Value;
                                                if (Contact.UpdateEmail(customerEmail, ref customer))
                                                {
                                                    crmService.Update(customer);
                                                }
                                                else
                                                {
                                                    commentaire += "\n" + customerEmail;
                                                }
                                                #region création prestation
                                                Entity newPrestation = new Entity("new_prestation")
                                                {
                                                    Attributes = new AttributeCollection()
                                                    {
                                                        new KeyValuePair <string, object>("new_demandid",
                                                                                          newIncident.ToEntityReference()),
                                                        new KeyValuePair <string, object>("new_subtypeid",
                                                                                          Prestation.GetSubTypeId(typeCode, crmService).ToEntityReference()),
                                                        new KeyValuePair <string, object>("new_categoryid",
                                                                                          Prestation.GetCategoryId("services", crmService)),
                                                        new KeyValuePair <string, object>("new_description",
                                                                                          commentaire)
                                                    }
                                                };
                                                #endregion

                                                if (crmService.GetService().Create(newPrestation) !=
                                                    Guid.Empty)
                                                {
                                                    returnCode = (int)CustomReturnCode.NewRequest;
                                                }
                                                //newPrestation.Attributes.Add();
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            result.SetError(-1,
                                                            "Impossible de créer la demande et ses prestations :\n" +
                                                            e.Message, e);
                                            //                                            new KeyValuePair<string, object>("title",
                                            //request.Element(requestNs + "text").Value)
                                        }
                                        crmService.Update(updateEmail);
                                    }
                                    else
                                    {
                                        returnCode = (int)CustomReturnCode.CustomerNotFound;
                                    }
                                }
                                #endregion

                                #region SMS
                                //File d'attente SMS
                                else
                                {
                                    if (queue.GetAttributeValue <string>("name").ToLower().Contains("sms"))
                                    {
                                        var number = Activity.GetEmailAttachement(email.GetAttributeValue <string>("description"), queue.GetAttributeValue <string>("name").ToLower()).Root;

                                        Guid contractId = Contrat.GetContractByPhone("+" + number.Element("font").Value, crmService);
                                        if (contractId != Guid.Empty)
                                        {
                                            List <Entity> contact = Contact.GetContactByPhoneOnContract(contractId,
                                                                                                        "+" + number.Elements("font").ToList()[1].Value, crmService);

                                            CheckRequest(contact, updateEmail, crmService, queue.GetAttributeValue <string>("name"));
                                        }
                                        else
                                        {
                                            returnCode = (int)CustomReturnCode.ContractNotFound;
                                        }

                                        //
                                    }
                                    else
                                    {
                                        returnCode = (int)CustomReturnCode.ContractNotFound;
                                    }
                                }
                                #endregion

                                #endregion
                            }
                        }
                    }
                    else
                    {
                        if (status == 100000001)
                        {
                            returnCode = (int)CustomReturnCode.MailClosed;
                        }
                    }
                }
                else
                {
                    returnCode = (int)CustomReturnCode.MailNotFound;
                    //result.SetError((int)CustomReturnCode.MailNotFound, customError.getErrorMessage((int)CustomReturnCode.MailNotFound));
                }
                result.SetError(returnCode, customError.getErrorMessage(returnCode));
            }
            catch (Exception e)
            {
                result.SetError((int)CustomReturnCode.Unknown, e.Message, e);
            }
            Dispose();
            return(result.getXml((Method == "post") ? new List <string> {
                messageId
            } : null));
        }