I am writting client application that uses Exchange Web Services managed API v.2.0
in order to connect to Exchange Web Services
. During testing (we follow TDD) I need load EmailMessage
object from saved .eml file. It’s easy find out that in order to store message
object of type EmailMessage
in .eml file we need call
message.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent)); |
that set MimeContent
property with byte array, and then save this value in .eml file.
Now we would like to code the reverse operation. Thus we need to do the following steps:
- Create empty
EmailMessage
object. - Load content of .eml file into
MimeContent
property. - Save
EmailMessage
object at Exchange server, that requires validExchangeService
object. - Load primary properties of the message, and then load attachments.
- Delete temporary message from Exchange server.
The code listed below demonstrates this workflow:
using System; using System.IO; using Microsoft.Exchange.WebServices.Data; namespace Exchange.Mail { public static class EmailMethods { public static EmailMessage LoadEmailMessage(ExchangeService service, string fileName) { // load data from file byte[] content; using (var file = File.OpenRead(fileName)) { content = new byte[file.Length]; file.Position = 0; file.Read(content, 0, (int)file.Length); } // create EmailMessage with mime content var message = new EmailMessage(service) { MimeContent = new MimeContent("UTF-8 ", content), }; message.Save(); message.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent)); if (message.HasAttachments) foreach (var attachment in message.Attachments) attachment.Load(); message.Delete(DeleteMode.HardDelete); // set additional properties SetProperty(message, EmailMessageSchema.ReceivedBy, new EmailAddress("User", "User@example.com")); message.From = new EmailAddress("Admin", "Admin@example.com"); } } }
The code of SetProperty
method is listed here.
- All used IP-addresses, names of servers, workstations, domains, are fictional and are used exclusively as a demonstation only.
- Information is provided «AS IS».