How do I get the real email address with Exchange web services?

好久不见. 提交于 2019-12-05 22:54:18
George

I'd like to answer my own question:

Dim instances As NameResolutionCollection
instances = service.ResolveName(mailItem.Sender.Address)
If instances.Count > 0 Then
    ResolveName = instances(0).Mailbox.Address
Else
    ResolveName = ""
End If

... where "service" is an ExchangeService object and mailItem.Sender.Address contains an X500 address (I think that's what it's called). mailItem.Sender.Address will contain an X500 type address if the sender is intern to your organisation as Jan Doggen pointed out.


I might recommend changing to the following:

If instances.Count > 0 Then
    ResolveName = instances(0).Mailbox.Address
Else
    ResolveName = i.Sender.Address
End If

By doing this the ResolveName will keep the original sender Email Address if the email is from an external source.

Quoting from How to: Get the SMTP Address of the Sender of a Mail Item:

"To determine the SMTP address for a received mail item, use the SenderEmailAddress property of the MailItem object. However, if the sender is internal to your organization, SenderEmailAddress does not return an SMTP address, and you must use the PropertyAccessor object to return the sender’s SMTP address."

The page gives a C# example, that you should be able to convert to VB.Net:

private string GetSenderSMTPAddress(Outlook.MailItem mail)
{
    string PR_SMTP_ADDRESS =
        @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
    if (mail == null)
    {
        throw new ArgumentNullException();
    }
    if (mail.SenderEmailType == "EX")
    {
        Outlook.AddressEntry sender =
            mail.Sender;
        if (sender != null)
        {
            //Now we have an AddressEntry representing the Sender
            if (sender.AddressEntryUserType ==
                Outlook.OlAddressEntryUserType.
                olExchangeUserAddressEntry
                || sender.AddressEntryUserType ==
                Outlook.OlAddressEntryUserType.
                olExchangeRemoteUserAddressEntry)
            {
                //Use the ExchangeUser object PrimarySMTPAddress
                Outlook.ExchangeUser exchUser =
                    sender.GetExchangeUser();
                if (exchUser != null)
                {
                    return exchUser.PrimarySmtpAddress;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return sender.PropertyAccessor.GetProperty(
                    PR_SMTP_ADDRESS) as string;
            }
        }
        else
        {
            return null;
        }
    }
    else
    {
        return mail.SenderEmailAddress;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!