Skip to main content
 首页 » 编程设计

c#之如何使用 EWS 托管 API 回复电子邮件

2024年05月29日53freeliver54

我创建了一个使用 EWS Managed API 2.2 的应用程序。 此应用程序使用拉取通知来获取新电子邮件并将电子邮件的副本保存在数据库中。

然后在应用程序中我想从数据库中获取电子邮件并回复它。 为了回复消息,我需要使用我存储在数据库中的 ItemId 从 EWS 中检索它。

当然我可以创建一个新的 EmailMessage 并发送它,但是新的电子邮件将具有不同的 ConversationId,这对于应用场景来说是 Not Acceptable 。

因此,为了实现这一点,我使用了以下代码行 EmailMessage.Bind(服务, itemId);

要使此方法起作用,我必须从我的数据库中实例化 ItemId,但 ItemId 构造函数仅将 UniqueId 作为参数,并使用 null ChangeKey 创建它。 如果我使用此 ItemId(具有 null ChangeKey),我会收到以下错误: Microsoft.Exchange.WebServices.Data.ServiceResponseException: 在商店中找不到指定的对象。

我认为这是因为空 ChangeKey。我对么? 有解决办法吗?

请您参考如下方法:

不使用 ItemId 来标识消息,而是使用 EntryID。使用 EntryID,您可以绑定(bind)到同一封电子邮件而无需 ChangeKey。

以下是此类属性的定义:

ExtendedPropertyDefinition EntryIDProperty = new ExtendedPropertyDefinition(0x0FFF, MapiPropertyType.Binary); 

当您搜索邮件时,请确保您指示 EWS 将此类属性包含在检索到的项目列表中。

下面是调用 FindItems 时获取 EntryID 的示例:

ExtendedPropertyDefinition EntryIDProperty = new ExtendedPropertyDefinition(0x0FFF, MapiPropertyType.Binary); 
 
ItemView item_view = new ItemView(10) { PropertySet = new PropertySet(ItemSchema.Id, EntryIDProperty) }; 
 
var result = service.FindItems(WellKnownFolderName.Inbox, item_view); 
 
foreach (var item in result.Items) 
{ 
    byte[] entry_id = (byte[])item.ExtendedProperties.Single(x => x.PropertyDefinition == EntryIDProperty).Value; 
 
    string entry_id_hex = ByteArrayToHexString(entry_id); //This is the entry ID that you should store 
} 

如果要使用 EmailMessage.Bind,请使用以下方法将 EntryID 转换为 ItemID:

此方法接受字符串 EntryID。

mailbox_address 是邮箱的 SMTP 地址(例如 test@domain.com)

“服务”是 ExchangeService 对象。

private ItemId ConvertEntryIdToItemId(string entryid, string mailbox_address, ExchangeService service) 
{ 
    AlternateId id = new AlternateId(IdFormat.HexEntryId, entryid, mailbox_address); 
 
    AlternateId new_id = (AlternateId)service.ConvertId(id, IdFormat.EwsId); 
 
    ItemId item_id = new_id.UniqueId; 
 
    return item_id; 
} 

现在您可以使用返回的 ItemId 来绑定(bind)您的 EmailMessages。