Exchange Web Services and reading an EmailMessage to memory
The Exchange Web Services Managed API is a great tool for exposing Exchange Web Services to a .NET programming environment. You are able to work with all the key features of an Exchange Mailbox, such as downloading messages. In my particular case, I’ve been capturing emails and storing them in a SharePoint document library.
The upload to SharePoint can be achieved by passing in a MemoryStream object - that is, you read an EmailMessage to memory, and then upload it to SharePoint. The FileAttachment object has a neat Load() method which allows you to read a FileAttachment to a MemoryStream:
`
foreach(FileAttachment fa in item.FileAttachments)
{
using(MemoryStream ms = new MemoryStream())
{
fa.Load(ms);
// Do something with your memorystream
}
}
`
Nice and simple. But for the EmailMessage itself, the process is a little different. You might ordinarily try and Serialise the EmailMessage object, but, unfortunately, this won’t work, as it’s not marked as Serializable. Instead, you have to access the MimeContent.Content property which is already a byte[]:
`
EmailMessage em = (EmailMessage)item;
PropertySet ps = new PropertySet(ItemSchema.MimeContent);
em.Load(ps);
using (MemoryStream ms = new MemoryStream(item.MimeContent.Content)) {
// etc.
}
`
You now have your EmailMessage in memory and do what you like with it. If you save it somewhere as a .eml file, then it will continue to behave and function like an email, with subject, sender, and attachments!