共用方式為


取得郵件項目寄件者 SMTP 位址

此範例會取得發件人的簡易郵件傳輸通訊協定 (郵件專案的 SMTP) 位址。

範例

若要判斷已接收郵件專案的 SMTP 位址,請使用 MailItem 物件的 SenderEmailAddress 屬性。 不過,如果寄件者是貴組織內部的, SenderEmailAddress 不會傳回 SMTP 位址,而且您必須使用 PropertyAccessor 物件傳回發件者的 SMTP 位址。

在下列程式代碼範例中,GetSenderSMTPAddress 會使用 PropertyAccessor 物件來取得未直接在 Outlook 物件模型中公開的值。 GetSenderSMTPAddress 接受 MailItem。 如果收到之 MailItemSenderEmailType 屬性值為 “EX”,則郵件的寄件者會位於您組織中的 Exchange 伺服器上。 GetSenderSMTPAddress 會使用 MailItem 物件的 Sender 屬性來取得以 AddressEntry 物件表示的發件者。 如果 AddressEntry 物件代表 Exchange 使用者,則此範例會呼叫 GetExchangeUser () 方法來傳回 AddressEntry 物件的 ExchangeUser 物件。 GetSenderSMTPAddress 接著會使用 ExchangeUser 物件的 PrimarySmtpAddress 屬性來傳回發件者 SMTP 位址。 如果發件者的 AddressEntry 物件不代表 ExchangeUser 物件,則會使用 PropertyAccessor 物件的 GetProperty (String) 方法,並使用 PR_SMTP_ADDRESS (PidTagSmtpAddress) 做為自變數,以傳回發件者的 SMTP 位址。

If you use Visual Studio to test this code example, you must first add a reference to the Microsoft Outlook 15.0 Object Library component and specify the Outlook variable when you import the Microsoft.Office.Interop.Outlook namespace. The using statement must not occur directly before the functions in the code example but must be added before the public Class declaration. The following line of code shows how to do the import and assignment in C#.

using Outlook = Microsoft.Office.Interop.Outlook;
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;
    }
}

另請參閱