Outlook 365插件无法获取Exchange邮件发件人SMTP地址问题
问题:Outlook 365插件无法获取Exchange发送邮件的发件人信息
我们正在开发一款Outlook 365插件,需要提取邮件信息生成文件,但收件箱中通过Exchange发送的邮件始终无法获取发件人信息。采用微软官方文档中的方法实现后,代码始终返回null。
原实现代码
private string GetSenderSMTPAddress(Microsoft.Office.Interop.Outlook.MailItem mail) { string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E"; if (mail == null) { throw new ArgumentNullException(); } if (mail.SenderEmailType == "EX") { Microsoft.Office.Interop.Outlook.AddressEntry sender = mail.Sender; if (sender != null) { //Now we have an AddressEntry representing the Sender if (sender.AddressEntryUserType == Microsoft.Office.Interop.Outlook.OlAddressEntryUserType. olExchangeUserAddressEntry || sender.AddressEntryUserType == Microsoft.Office.Interop.Outlook.OlAddressEntryUserType. olExchangeRemoteUserAddressEntry) { //Use the ExchangeUser object PrimarySMTPAddress Microsoft.Office.Interop.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; } }
当前问题点
代码在以下环节返回null:获取到ExchangeUser对象后,访问其PrimarySmtpAddress属性时无有效返回:
if (exchUser != null) { return exchUser.PrimarySmtpAddress; }
解决方案
1. 优先通过PropertyAccessor读取MAPI属性
跳过ExchangeUser对象的依赖,直接读取PR_SMTP_ADDRESS属性,即使是Exchange类型的地址条目也能兼容。修改后的代码如下:
private string GetSenderSMTPAddress(Microsoft.Office.Interop.Outlook.MailItem mail) { const string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E"; if (mail == null) throw new ArgumentNullException(nameof(mail)); if (mail.SenderEmailType == "EX") { var sender = mail.Sender; if (sender != null) { try { // 直接读取SMTP地址属性 return sender.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string; } catch (Exception) { // 读取失败时回退到原逻辑 if (sender.AddressEntryUserType == Microsoft.Office.Interop.Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || sender.AddressEntryUserType == Microsoft.Office.Interop.Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { var exchUser = sender.GetExchangeUser(); return exchUser?.PrimarySmtpAddress; } return null; } } return null; } else { return mail.SenderEmailAddress; } }
2. 尝试读取备用MAPI属性
如果PR_SMTP_ADDRESS读取失败,可以尝试读取PR_SENDER_EMAIL_ADDRESS属性(标签为0x0C1F001E),替换对应读取逻辑即可:
const string PR_SENDER_EMAIL_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x0C1F001E"; // 在代码中使用 return sender.PropertyAccessor.GetProperty(PR_SENDER_EMAIL_ADDRESS) as string;
3. 检查权限与配置
- 确保插件拥有足够权限访问Exchange用户信息,尤其是跨租户或外部Exchange用户场景。
- 确认Exchange服务器地址簿配置允许客户端获取用户SMTP地址。
内容的提问来源于stack exchange,提问作者velteyn
相关产品推荐
相关产品推荐

