我正在使用的系统有一个要求,即将刚发送的电子邮件的MimeContent
存储在本地数据库中。我对Exchange的工作方式的理解是,它将在服务器上创建MimeContent
,除非查询该刚刚发送的消息,否则我将无法访问它。
所以,我采取的步骤是:
-发送电子邮件并获取Id
message.SendAndSaveCopy();
return message.Id.UniqueId;
-使用新ID获取刚刚发送的EmailMessage
ExchangeService exchangeService = ExchangeService;
var properties = new List<PropertyDefinitionBase>
{
ItemSchema.MimeContent
};
EmailMessage message = EmailMessage.Bind(exchangeService, new ItemId(messageId), new PropertySet(BasePropertySet.IdOnly, properties));
当此代码不间断运行时,它将起作用。返回的Id
仍然有效(消息在发件箱文件夹中),我得到了结果。但是,如果我放慢速度一秒钟,则该ID不再有效(我想它现在已移至已发送的文件夹中)。
我不能这样保留它,因为不能保证我会及时回到服务器来检索带有该Id
的消息。
如果有一种解决方案可以使我不必再次向该服务查询消息,那将会很不错。但是,如果没有,是否可以使用Id
和ChangeKey
来获取刚刚发送的电子邮件?
答案 0 :(得分:0)
最终回答了我自己的问题。为此,我在自己控制的每封电子邮件中添加了一个自定义属性。然后,我使用相同的值来搜索电子邮件。我在查询之间的文件夹之间移动电子邮件时遇到了一些问题,但现在已进行排序。
将其定义在某个地方,我将其放在我的EmailProvider类中:
private readonly PropertyDefinitionBase _TempEmailId = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "TempEmailId", MapiPropertyType.String);
然后在发送电子邮件之前将其添加:
string messageId = null;
if (getTempId)
{
messageId = Guid.NewGuid().ToString();
message.SetExtendedProperty((ExtendedPropertyDefinition) _TempEmailId, messageId);
}
message.SendAndSaveCopy();
return messageId;
最后,使用messageId
获得MimeContent
(或您想要的其他任何属性):
/// <summary>
/// Get the mime content for an email just sent
/// </summary>
/// <param name="messageId"></param>
/// <returns></returns>
public byte[] GetJustSentMimeContent(string messageId)
{
ExchangeService exchangeService = ExchangeService;
// Use the following search filter to get mail with TempEmailId set to what we just got
var searchCriteria = new SearchFilter.IsEqualTo(_TempEmailId, messageId);
var itemView = new ItemView(1) {PropertySet = new PropertySet(BasePropertySet.IdOnly)};
byte[] GetMimeContent(WellKnownFolderName folder)
{
var items = exchangeService.FindItems(folder, searchCriteria, itemView);
if (items.TotalCount > 0)
{
// if it's still in there, try and load the properties for it
exchangeService.LoadPropertiesForItems(items,
new PropertySet(BasePropertySet.IdOnly,
ItemSchema.MimeContent));
var emailMessage = (EmailMessage) items.First();
// if the content has been loaded, return it
if (emailMessage.MimeContent != null)
return emailMessage.MimeContent.Content;
}
return null;
}
// check the drafts folder to see if it's still in there
var mimeContent = GetMimeContent(WellKnownFolderName.Drafts);
if (mimeContent != null)
return mimeContent;
// if at this point, either:
// - email was moved to SentItems before the first search was done
// - or email was found in Drafts but then moved to SentItems but before the MimeContent could be loaded. Need to restart the process and find the email in SentItems instead
// should be in here (sentItems) now, try and load the properties for it
return GetMimeContent(WellKnownFolderName.SentItems);
}