I write 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 create 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:
1. Create empty EmailMessage
object.
2. Load content of .eml file into MimeContent
property.
3. Save EmailMessage
object at Exchange server, that requires valid ExchangeService
object.
4. Load primary properties of the message, and then load attachments.
5. Delete temporary message from Exchange server.
The code listed below shows this workaround:
*************************************************
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.
1. All used IP-addresses, names of servers, workstations, domains, are fictional and are used exclusively as a demonstration only.
2. Information is provided «AS IS».
[…] 1. Создание сертификатов Exchange Server. 2. Настройка Exchange Server для использования EWS. 3. Использование ссылок на библиотеки по нестандартному пути. 4. Установка свойств объекта EmailMessage. 5. Создание объекта EmailMessage из .eml файла. […]