Thursday, September 1, 2016

EWS: Sending a collection of e-mails using CreateItems

Exchange Web Services (EWS) is an API for getting and sending content to an Exchange server. This post will explain how to send a collection of e-mails with one call to EWS, and identify one if it's shortcomings.

First you will need a list of Item objects. In EWS, the Item class is a generic item. Classes such as Appointment, Contact, ContactGroup, EmailMessage, PostItem, and Task all inherit from the Item class. As such, the CreateItems() method can create any object that inherits from the Item class. This example, will demonstrate using EmailMessage objects to create real e-mails.

List<Item> items = new List<Item>();
EmailMessage email_1 = new EmailMessage(_service)
{
    ToRecipients = { new EmailAddress("foo@bar.com") },
    Subject = "Hello",
    Body = "Hello World!"
};
EmailMessage email_2 = new EmailMessage(_service)
{
    ToRecipients = { new EmailAddress("foo2@bar.com") },
    Subject = "Hello 2",
    Body = "Hello World!"

};
items.Add(email_1);
items.Add(email_2);

Then, pass the list of Items to the CreateItems() method.

ServiceResponseCollection<ServiceResponse> responseCollection = _service.CreateItems(items, inboxFolder.Id, MessageDisposition.SendOnly, null);

That's it. 

There are limitations on the number of items you will be allowed to send at once due to Exchange server policies on throttling, etc. Next, consider adding an attachment to these e-mails..

email_1.Attachments.AddFileAttachment(attachment1);
email_2.Attachments.AddFileAttachment(attachment2);

Then, if we try to create these e-mails with attachments using the CreateItems call again, this time it will not work. This is because, "under the hood, the workflow for sending emails with attachments is: CreateItem, CreateAttachment, and then SendItem. CreateItems is a batch of CreateItem calls, it doesn't contain the workflow to break out items with attachments" (referencing StackOverflow post)

So, the way to send e-mails with attachments using EWS is one at a time, and the way to send a group of emails without attachments is using CreateItems.

References

http://stackoverflow.com/questions/23206057/ews-managed-api-get-response-from-sent-mail-with-attachments

No comments: