Luciano Schafer
Luciano Schafer

Reputation: 45

how to obtain email address from ews contacts

im using this code to get the contacts from outlook:

        foreach (var v in svc.FindItems(WellKnownFolderName.Contacts,
                                        new ItemView(20)))
        {
            Contact contact = v as Contact;
            ContactGroup contactGroup = v as ContactGroup;

            if (contact != null)
            {   
                 Console.WriteLine("Contact: {0} <{1}>",
                 contact.DisplayName,
                 contact.EmailAddresses[EmailAddressKey.EmailAddress1]);
            }
        }

i'm need to get de email direction ([email protected]) but i get this in email address field:

"/o=companyname/ou=FIRST ADMINISTRATIVE GROUP/cn=RECIPIENTS/cn=username"

Upvotes: 4

Views: 4713

Answers (2)

Nikki9696
Nikki9696

Reputation: 6348

You can also get it by calling Load() method, and this seems to perform better. See https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8760c6a5-09c6-438a-a70a-c4063645cc76/exchange-web-service-api-contact-email-address

Calling Load fixed it for me.

Upvotes: 0

Odrai
Odrai

Reputation: 2353

Your 'email address' is in the form of an Exchange distinguished name. It's just not an SMTP address.

To get SMTP email address:

Simple code example

NameResolutionCollection nd = service.ResolveName(contact.EmailAddresses[EmailAddressKey.EmailAddress1].Address);
       foreach (NameResolution nm in nd)
       {
           if (nm.Mailbox.RoutingType == "SMTP")
           {
               //Console.WriteLine(nm.Mailbox.Address);
               emailAddress1 = nm.Mailbox.Address;
           }
       }

Improved code

EmailAddress email;
if (contact.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress1, out email))
{
    person.Email = GetResolvedEmailAddress(email.Address, svc);
}

private static Dictionary<String, String> ResolvedEmailAddressCache = new Dictionary<String, String>();
    private static String GetResolvedEmailAddress(string address, ExchangeService svc)
    {
        if (ResolvedEmailAddressCache.ContainsKey(address))
            return ResolvedEmailAddressCache[address];

        NameResolutionCollection nd = svc.ResolveName(address);
        foreach (NameResolution nm in nd)
        {
            if (nm.Mailbox.RoutingType == "SMTP")
            {
                ResolvedEmailAddressCache.Add(address, nm.Mailbox.Address);
                return nm.Mailbox.Address;
            }
        }

        ResolvedEmailAddressCache.Add(address, address);
        return address;
    }

Upvotes: 5

Related Questions