次の方法で共有


メール アイテムの差出人の SMTP アドレスを取得する

この例では、メール アイテムの差出人の簡易メール転送プロトコル (SMTP) アドレスを取得します。

受信したメール アイテムの SMTP アドレスを確認するには、MailItem オブジェクトの SenderEmailAddress プロパティを使用します。 ただし、組織の内部の送信者については、SenderEmailAddress によって SMTP アドレスは返されません。その送信者の SMTP アドレスを返す PropertyAccessor オブジェクトを使用する必要があります。

次のコード例では、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 アドレスを返します。

Visual Studio を使用してこのコード例をテストする場合、Microsoft.Office.Interop.Outlook 名前空間をインポートするときに、まず Microsoft Outlook 15.0 オブジェクト ライブラリ コンポーネントへの参照を追加し、Outlook 変数を指定します。 using ステートメントは、コード例の関数の前に直接置くことはできません。パブリッククラス宣言の前に追加する必要があります。 次のコード行は、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;
    }
}

関連項目