Search code examples
c#outlookvstooutlook-addinadd-in

Get first and last name in VSTO C#


I have to get the first and last name separately of the first recipient while performing Reply/ReplyAll actions.

Currently, I am doing this like:

                    #region Extracting Last and First Name

                    string LName = null;
                    string FName = null;

                    if (mailItem.Recipients[1].AddressEntry.GetExchangeUser() == null)
                    {
                        FName = FirstName(mailItem.Recipients[1].Name);
                        LName = LastName(mailItem.Recipients[1].Name);
                    }
                    else
                    {
                        FName = mailItem.Recipients[1].AddressEntry.GetExchangeUser().FirstName;
                        LName = mailItem.Recipients[1].AddressEntry.GetExchangeUser().LastName;
                    }

                    #endregion

[NOTE: In the above region, FirstName(string name) and LastName(string name) methods split name by space and return first and last element respectively]

But, for some recipients, it returned the whole email address. :(

After exploring Outlook, I found that the above code is getting the "Display as" field(inside contact window, refer below image), and performing operations over it, which is not the correct way to extract first and last name.

And inside the "Check Full Name" window I got all details separated correctly(refer below image), which is an actual requirement.

So, how I can get the value of "First" and "Last" from the "Check Full name" Window? Or do we have any better way to do this?

Refer this image: enter image description here


Solution

  • Firstly, you are accessing mailItem.Recipients[1].AddressEntry.GetExchangeUser() three (!!!) times. Do that only once - that line of code ends up retrieving 6 (!!!) brand new COM objects every time.

    Secondly, if the recipient is a contact rather than a GAL user, use AddressEntry.GetContact() (do that only once please) - once you have the ContactItem object, you can use its FirstName and LastName properties.