Outlook账户:如何获取Exchange邮箱地址?
如何获取Outlook Exchange账户的邮箱地址?
你遇到的问题很典型——Exchange账户默认返回的是X.500格式的专有地址(就是你看到的/O=FIRST ORGANIZATION/...这种),而不是我们常用的SMTP邮箱地址。要拿到正确的邮箱地址,你需要针对Exchange账户做特殊处理,通过AddressEntry对象获取对应的Exchange用户实例,再提取SMTP地址。
先看你原来的代码:
foreach (Outlook.Account account in accounts) { Debug.Print("DisplayName: " + account.DisplayName); Debug.Print("UserName: " + account.UserName); Debug.Print("CurrentUser.Address: " + account.CurrentUser.Address); //email address or long Exchange address Debug.Print("CurrentUser.Name: " + account.CurrentUser.Name); Debug.Print("CurrentUser.AddressEntry.Address: " + account.CurrentUser.AddressEntry.Address); Debug.Print("DeliveryStore.DisplayName: " + account.DeliveryStore.DisplayName); }
对应的运行结果:
非Exchange账户运行结果:
DisplayName: Edgar Test Account UserName: Edgar Tester CurrentUser.Address: edgar@testtest.com CurrentUser.Name: Edgar Tester CurrentUser.AddressEntry.Address: edgar@testtest.com DeliveryStore.DisplayName: Edgar Tester
Exchange账户运行结果:
DisplayName: User Name UserName: 000300KJDFA6220 CurrentUser.Address: /O=FIRST ORGANIZATION/OU=EXCHANGE ADMINISTRATIVE GROUP(FYDIAASFDSFLT)/CN=RECIPIENTS/CN=00458787FA6220 CurrentUser.Name: /O=FIRST ORGANIZATION/OU=EXCHANGE ADMINISTRATIVE GROUP(FYDLKHHKLSPDLT)/CN=RECIPIENTS/CN=0054654DFA6220 CurrentUser.AddressEntry.Address: /O=FIRST ORGANIZATION/OU=EXCHANGE ADMINISTRATIVE GROUP(FYDIDADS23SPDLT)/CN=RECIPIENTS/CN=0058876220 DeliveryStore.DisplayName: User Name
修改后的解决方案代码
foreach (Outlook.Account account in accounts) { Debug.Print("DisplayName: " + account.DisplayName); Debug.Print("UserName: " + account.UserName); Outlook.AddressEntry addrEntry = account.CurrentUser.AddressEntry; Debug.Print("CurrentUser.AddressEntry.Address: " + addrEntry.Address); // 判断当前账户是否为Exchange类型 if (addrEntry.AddressUserType == Outlook.OlAddressUserType.olExchangeUserAddressEntry) { // 获取Exchange用户对象 Outlook.ExchangeUser exchUser = addrEntry.GetExchangeUser(); if (exchUser != null) { // 提取SMTP邮箱地址 Debug.Print("Exchange User SMTP Address: " + exchUser.PrimarySmtpAddress); // 释放COM对象,避免内存泄漏 exchUser.Dispose(); } } else { // 非Exchange账户直接使用现有地址 Debug.Print("SMTP Address: " + addrEntry.Address); } Debug.Print("DeliveryStore.DisplayName: " + account.DeliveryStore.DisplayName); Debug.Print("---"); }
关键说明
- 判断账户类型:通过
AddressEntry.AddressUserType属性检查是否为olExchangeUserAddressEntry,这是最准确的判断方式。你也可以通过addrEntry.Type == "EX"来判断,不过前者更规范。 - 获取Exchange用户对象:调用
GetExchangeUser()方法可以拿到Exchange专属的用户实例,这个实例包含了我们需要的SMTP地址。 - 释放COM资源:Outlook的COM对象需要手动调用
Dispose()释放,否则容易造成内存泄漏,这点一定要注意。
修改后,Exchange账户就能输出正常的SMTP邮箱地址了,比如user@yourdomain.com这种格式。
内容的提问来源于stack exchange,提问作者Edgar
相关产品推荐
相关产品推荐

