[VSTO] How to find the SMTP address of a mail’s sender for a MailItem ?

June 13th, 2012 | Posted by Tom in .NET | Article | VSTO | Read: 1,731

Given a particular MailItem, the method below will help you to get the SMTP address of the person who send the email. The code is simple but take care of the fact that, in case of an Exchange user, we cant to get the SMTP address (and not the X.500 address):

public static string GetSenderEmailAddress(Outlook.MailItem mailItem)

{

    var propSMTP = “http://schemas.microsoft.com/mapi/proptag/0x39FE001F”;

    string emailAddress = string.Empty;

 

    if (mailItem.Sender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry)

    {

        var exchangeUser = mailItem.Sender.GetExchangeUser();

        if (exchangeUser != null)

        {

            emailAddress = exchangeUser.PrimarySmtpAddress;

 

            exchangeUser.ReleaseComObject();

        }

    }

    else

    {

        emailAddress = (string)mailItem.Sender.PropertyAccessor.GetProperty(propSMTP);

    }

 

    return emailAddress;

}

The method use the following extension method to release the COM object:

public static void ReleaseComObject(this object obj)

{

    if (obj != null && Marshal.IsComObject(obj))

        Marshal.ReleaseComObject(obj);

}

Note that the code can be easily modified to be used with the email’s recipients or, in fact, with any AddressEntry object !

Please, note that the code use the PropertyAccessor method so it’ll work only for Outlook version > 2007.

 

Happy coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register



Leave a Reply