Trabalhando com Contatos no Exchange Server

Obtendo Contatos com EWS

O Aspose.Email fornece a classe EWSClient para se conectar ao Microsoft Exchange Server usando os Serviços Web do Exchange. Os exemplos de código a seguir usam os Serviços Web do Exchange para ler todos os contatos. O seguinte exemplo de código mostra como obter contatos com EWS.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create instance of IEWSClient class by giving credentials
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
// List all the contacts
Contact[] contacts = client.GetContacts(client.MailboxInfo.ContactsUri);
foreach (MapiContact contact in contacts)
{
// Display name and email address
Console.WriteLine("Name: " + contact.NameInfo.DisplayName + ", Email Address: " + contact.ElectronicAddresses.Email1);
}

Resolver Contatos usando o Nome do Contato

O seguinte exemplo de código mostra como obter contatos com EWS.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create instance of IEWSClient class by giving credentials
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
// List all the contacts
Contact[] contacts = client.ResolveContacts("Changed Name", ExchangeListContactsOptions.FetchPhoto);
foreach (MapiContact contact in contacts)
{
// Display name and email address
Console.WriteLine("Name: " + contact.NameInfo.DisplayName + ", Email Address: " + contact.ElectronicAddresses.Email1);
}

Determinar o Formato das Notas de Contato

O Aspose.Email.Mail.Contact.NotesFormat especifica o tipo de formato de texto das notas de contato definido pelo enumerador Aspose.Email.TextFormat.

Buscar Contato usando o Id

Um contato específico pode ser recuperado do servidor usando seu id de contato, conforme mostrado no seguinte exemplo de código.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
Contact fetchedContact = client.GetContact(id);

Adicionando Contatos

A classe EWSClient pode usar o método CreateContact() para adicionar informações de contato a um Exchange Server. O método CreateContact() recebe um objeto Contact como parâmetro de entrada.

Para adicionar contatos a um Exchange Server:

  1. Inicialize o EWSClient com o endereço e credenciais.
  2. Inicialize o objeto Contact com as propriedades desejadas.
  3. Chame o método CreateContact para adicionar o contato ao Exchange Server.

O Aspose.Email fornece a classe EWSClient para se conectar ao Microsoft Exchange Server usando os Serviços Web do Exchange. Os exemplos de código mostram como usar os Serviços Web do Exchange para adicionar contatos a um Exchange Server.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Set mailboxURI, Username, password, domain information
string mailboxUri = "https://ex2010/ews/exchange.asmx";
string username = "test.exchange";
string password = "pwd";
string domain = "ex2010.local";
NetworkCredential credentials = new NetworkCredential(username, password, domain);
IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credentials);
//Create New Contact
Contact contact = new Contact();
//Set general info
contact.Gender = Gender.Male;
contact.DisplayName = "Frank Lin";
contact.CompanyName = "ABC Co.";
contact.JobTitle = "Executive Manager";
//Add Phone numbers
contact.PhoneNumbers.Add(new PhoneNumber { Number = "123456789", Category = PhoneNumberCategory.Home });
//contact's associated persons
contact.AssociatedPersons.Add(new AssociatedPerson { Name = "Catherine", Category = AssociatedPersonCategory.Spouse });
contact.AssociatedPersons.Add(new AssociatedPerson { Name = "Bob", Category = AssociatedPersonCategory.Child });
contact.AssociatedPersons.Add(new AssociatedPerson { Name = "Merry", Category = AssociatedPersonCategory.Sister });
//URLs
contact.Urls.Add(new Url { Href = "www.blog.com", Category = UrlCategory.Blog });
contact.Urls.Add(new Url { Href = "www.homepage.com", Category = UrlCategory.HomePage });
//Set contact's Email address
contact.EmailAddresses.Add(new EmailAddress { Address = "Frank.Lin@Abc.com", DisplayName = "Frank Lin", Category = EmailAddressCategory.Email1 });
try
{
client.CreateContact(contact);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Atualizando Contatos

As informações de contato podem ser atualizadas usando o Microsoft Outlook. O Aspose.Email também pode atualizar informações de contato no Exchange Server usando o Serviço Web do Exchange (EWS). O método IEWSClient UpdateContact pode atualizar informações de contato no Exchange Server.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credentials);
// List all the contacts and Loop through all contacts
Contact[] contacts = client.GetContacts(client.MailboxInfo.ContactsUri);
Contact contact = contacts[0];
Console.WriteLine("Name: " + contact.DisplayName);
contact.DisplayName = "David Ch";
client.UpdateContact(contact);

Deletando Contatos

A classe EWSClient permite que o método DeleteContact acesse e delete contatos da pasta de contatos de um Exchange Server. Este método recebe o ID do contato ou MapiContact como parâmetro de entrada.

Para deletar contatos de um Exchange Server:

  1. Inicialize o ExchangeWebServiceClient com o endereço e credenciais.
  2. Delete um contato usando seu ID.
  3. Delete um contato chamando o método DeleteContact com MapiContact como parâmetro de entrada.

Os seguintes exemplos de código mostram como deletar contatos de um servidor Exchange usando o serviço web do Exchange.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create instance of EWSClient class by giving credentials
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
string strContactToDelete = "John Teddy";
Contact[] contacts = client.GetContacts(client.MailboxInfo.ContactsUri);
foreach (Contact contact in contacts)
{
if (contact.DisplayName.Equals(strContactToDelete))
client.DeleteItem(contact.Id.EWSId, DeletionOptions.DeletePermanently);
}
client.Dispose();

Trabalhando com Propriedades Estendidas de Contatos no Exchange Server


 IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
 
//As propriedades estendidas necessárias devem ser adicionadas para criá-las ou lê-las do Exchange Server

string[] extraFields = new string[] {{ "User Field 1", "User Field 2", "User Field 3", "User Field 4" }};

foreach (string extraField in extraFields)

    client.ContactExtendedPropertiesDefinition.Add(extraField);

//Criar um contato de teste no Exchange Server

Contact contact = new Contact();

contact.DisplayName = "EMAILNET-38433 - " + Guid.NewGuid().ToString();

foreach (string extraField in extraFields)

    contact.ExtendedProperties.Add(extraField, extraField);

string contactId = client.CreateContact(contact);

//recuperar o contato de volta do servidor após algum tempo

Thread.Sleep(5000);

contact = client.GetContact(contactId);

//Analisar as propriedades estendidas do contato

foreach (string extraField in extraFields)

    if (contact.ExtendedProperties.ContainsKey(extraField))

        Console.WriteLine(contact.ExtendedProperties[extraField].ToString());