已经有一些关于这个问题的问答,但是我遇到了不同的问题。其他问题上发布的解决方案对我没有用,我认为原因是我试图获取发件人发送的电子邮件的SMTP地址,而不是来自其他人并保存在邮件文件夹中的电子邮件。
我的目标
简单地说,我正在编写一个 Outlook 插件,该插件挂钩 "ItemSend" 事件,并运行一个函数,在用户点击 "发送" 时显示发送者的电子邮件 (SMTP) 地址。
问题
当从 Exchange 邮箱发送电子邮件时,我无法获取 SMTP 地址。相反,mail.SenderEmailAddresss
给出了一个 X400 地址,其他我找到的方法要么引发异常,要么根本没有返回电子邮件地址。
GetSenderSMTPAddress(mail)
返回空白输出
mail.SenderEmailAddresss
的结果是:/o=Company Organisation/ou=Exchange Administrative Group (ABC123T)/cn=Recipients/cn=abc123-
mail.Sender.Address
导致 Exception thrown: 'System.NullReferenceException' in OutlookTesting.dll
我目前拥有的代码
namespace OutlookTesting
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.ItemSend += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
}
void Application_ItemSend(object Item, ref bool Cancel)
{
if (Item is Outlook.MailItem)
{
Outlook.MailItem mail = (Outlook.MailItem)Item;
Debug.WriteLine("Using GetSenderSMTPAddress function: " + GetSenderSMTPAddress(mail));
Debug.WriteLine("Using mail.SenderEmailAddresss: " + mail.SenderEmailAddress);
Debug.WriteLine("Using mail.Sender.Address: " + mail.Sender.Address);
}
}
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;
}
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
}
#endregion
}
}
我尝试过的其他方法
我尝试了这里提供的解决方案:https://learn.microsoft.com/en-us/office/client-developer/outlook/pia/how-to-get-the-smtp-address-of-the-sender-of-a-mail-item。但是这个方法并没有起作用,反而报了一个NullReferenceException的错误。
我也曾回退到假定默认邮箱是发件人的电子邮件地址,但对于拥有多个邮箱的用户来说,这是不可取的。
结束思考
我考虑的唯一解决方案(除了使用第三方插件)是循环遍历账户上的每个邮箱,获取X400地址(如果是Exchange邮箱),并将其与电子邮件地址放入一个数组中。当发送邮件时,从正在发送的邮件中获取X400地址,匹配到账户的X400地址,然后就可以得到电子邮件地址了。不确定这是否可行或是一个好的解决方案。
Environment.Username
获取已登录用户的用户名,然后使用此信息从Exchange获取发件人电子邮件地址吗? - joeschwa