从Outlook.MailItem获取发件人活动目录用户主体

时间:2012-08-09 08:26:55

标签: c# active-directory outlook-addin outlook-2007

我正在为Outlook 2007开发Outlook插件。简而言之:当用户打开电子邮件时,我需要获取电子邮件发件人的活动目录用户主体对象。

我想要实现的目标:

  1. 获取此电子邮件的发件人
  2. 获取此发件人背后的相应活动目录帐户
  3. 获取此广告帐户的特定属性(“physicalDeliveryOfficeName”)
  4. 我可以处理第1步和第3步,但我不知道如何获取exchange-user-account和活动目录帐户之间的链接

    我尝试了什么

    string senderDisplayName = mailItem.SenderName;
    

    由于重复,无法通过displayname查找用户

    string senderDistinguishedName = mailItem.SenderEmailAddress;
    

    这将返回类似“O = Company / OU = Some_OU / CN = RECIPIENTS / CN = USERNAME”的内容 我可以提取此字符串的用户名,但此“用户名”是用户邮箱的用户名或类似名称。它并不总是与活动目录用户名匹配。

    有没有办法让活动目录用户位于sender-object后面?

    环境

    • Outlook 2007 / C#.NET 4
    • Exchange 2010
    • Active Directory

1 个答案:

答案 0 :(得分:2)

下面介绍的技术假设 Exchange邮箱别名与您的 AD帐户ID 相匹配。

首先,您需要从Exchange地址创建Recipient,将Recipient解析为ExchangeUser,然后集成PrincipalContext以按帐户ID搜索AD。找到UserPrincipal后,您可以在DirectoryEntry查询自定义AD属性。

string deliveryOffice = string.Empty;
Outlook.Recipient recipient = mailItem.Application.Session.CreateRecipient(mailItem.SenderEmailAddress);
if (recipient != null && recipient.Resolve() && recipient.AddressEntry != null) 
{
    Outlook.ExchangeUser exUser = recipient.AddressEntry.GetExchangeUser();
    if (exUser != null && !string.IsNullOrEmpty(exUser.Alias))
    {
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
        {
            UserPrincipal up = UserPrincipal.FindByIdentity(pc, exUser.Alias); 
            if (up != null)
            {
                DirectoryEntry directoryEntry = up.GetUnderlyingObject() as DirectoryEntry;
                if (directoryEntry.Properties.Contains("physicalDeliveryOfficeName"))
                    deliveryOffice = directoryEntry.Properties["physicalDeliveryOfficeName"].Value.ToString();
            }
        }
    }
}

注意 对于AD集成,您需要引用System.DirectoryServicesSystem.DirectoryServices.AccountManagement