【发布时间】:2021-03-08 09:49:26
【问题描述】:
已经有一些关于此的问题,但我面临一个不同的问题。在其他问题上发布的解决方案对我不起作用,我怀疑原因是我正在尝试获取外发电子邮件的发件人电子邮件地址,而不是从其他人发送并位于邮件文件夹中的电子邮件地址.
我想做什么
简单地说,我正在编写一个 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://docs.microsoft.com/en-us/office/client-developer/outlook/pia/how-to-get-the-smtp-address-of-the-sender-of-a-mail-item。这不起作用,而是给出了 NullReferenceException。
我也回过头来假设默认邮箱是发件人的电子邮件地址,但这对于拥有多个邮箱的人来说是个坏主意。
结束的想法
我认为唯一的解决方案(除了 3rd 方插件)是遍历帐户上的每个邮箱,获取 X400 地址(如果交换邮箱)并将电子邮件地址放入数组中。发送邮件时,从外发邮件中获取 X400,将其与帐户的 X400 匹配,然后我将获得电子邮件地址。不确定这是否可行,甚至是一个不错的解决方案。
【问题讨论】:
-
查看其他需要获取发件人电子邮件地址的 Outlook 插件,发现它们不需要。他们使用手动方法来指定电子邮件地址,所以看起来这是不可能的。
-
您是否尝试过使用
Environment.Username获取登录个人的用户名,然后使用此信息从Exchange 获取发件人电子邮件地址?
标签: c# vsto outlook-addin