Programming Outlook: Sender or Receiver SMTP-Address

Tags: outlook, smtp

In case you programm an Outlook-Extension and need to retrieve the Email-Address of the sender or the recipient of an email, you may find this snippet usefull: When the sender is an internal sender of you Exchange-Organization you will normally see the X400 address entry. This snippets will return the smtp-address for you.

const string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

public static string GetRecipientSMTPAddresses(Outlook.MailItem mail) {
    string result = string.Empty;
    foreach(Outlook.Recipient recipient in mail.Recipients){
        string smtpAddress = GetSmtpAddress(recipient.AddressEntry);
        result += smtpAddress + ";";
    }
    return result.TrimEnd(';');
}

public static string GetSenderSMTPAddress(Outlook.MailItem mail) {
    if (mail.SenderEmailType == "EX") {
        Outlook.AddressEntry sender =  mail.Sender;
        if (sender != null) {
            return GetSmtpAddress(sender);
        } else {
            return null;
        }
    } else {
        return mail.SenderEmailAddress;
    }
}

public static string GetSmtpAddress(Outlook.AddressEntry addressEntry) {
    //Now we have an AddressEntry representing the Sender
    if (addressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry
        || addressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) {

        //Use the ExchangeUser object PrimarySMTPAddress
            Outlook.ExchangeUser exchUser = addressEntry.GetExchangeUser();
        if (exchUser != null) {
            return exchUser.PrimarySmtpAddress;
        } else {
            return null;
        }
    } else if (addressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olSmtpAddressEntry) {
        return addressEntry.Address;
    } else {
        return addressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string;
    }
}

 

Greets – Helmut

Add a Comment