<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

Sending email with EWS (Exchange Web Service) Managed API

Abhay Wagh Nov 09, 2017

Microsoft EWS Exchange Web Service

Sending-email-with-EWS-managed-API.jpg

Microsoft Exchange server provides web services which are called as EWS to provide access to Exchange server data. To communicate with this web services Microsoft provides API’s called as EWS Managed APIs. Using these API’s we can build client application which can send, read, and reply to email messages from the exchange server, and can do tasks like adding, updating, canceling appointments. There are various methods provided by API’s to achieve various operations on exchange server. In this blog we will discuss how to send email messages through EWS managed API’s using .Net client application.

As a starting point, first add Microsoft.Exchange.WebServices reference in your .Net client application.

Configure Exchange service

ExchangeService class in EWS is used to configure credentials, exchange URL and service binding to be used for sending message.

  • Initiate exchange service object and specify the exchange version
private ExchangeService _service = new ExchangeService(ExchangeVersion.Exchange2013);

Providing Exchange server version with service object will indicate contract that server should use to process the request. Specifying version will enable to access properties and methods available in that particular version. EWS API supports from Exchange 2007 SP1 to Office 365 and Exchange Online.

  • Credentials to use to login to exchange server
Setting UseDefaultCredentials 'to true' will use currently logged on windows credentials and if set 'to false' we need to specify the credentials using WebCredentials object.

_service.UseDefaultCredentials = False;
_service.Credentials = New WebCredentials (username, password, DomainName);

  • Setting service URL
URL property is used to specify the service endpoint to be used for sending email. Exchange server expose service as <domain name>/EWS/Exchange.asmx. We need to specify service URL for communication.

_service.Url = New Uri("https://mydomain.com/ews/Exchange.asmx");

  • Timeout settings
You can also set timeout property to set request timeout. In case of situations such as conjunction in service when large number of users trying to send message at the same time this will help to terminate request after specific time and display relevant message in client application instead of waiting for Exchange service to server or terminate the request.

_service.Timeout = 200000;

Once the service configuration is done next step is to configure message to be sent using service object.

Configure Email message

EmailMessage class is used to setup message to be send. You can create, update, delete message using this class. Class provides various methods and properties.

  • Create email message object
Initialize EmailMessage class object with ExchangeService object

EmailMessage msg = new EmailMessage(_service);

  • Properties in message
msg.Subject = "Send message through EWS Managed API";

MessageBody msgBody = new MessageBody();
msgBody.BodyType = BodyType.HTML;
msgBody.Text = "A draft email message with the subject";

msg.Body = msgBody;

EWS Api’s provide two option for body type HTML or Text format. To send message as plain text set BodyType to Text, for HTML message specify type as HTML. You can also assign HTML string to Text property to send email with HTML formatting.

  • Adding attachments to message body
User can add attachments to the message using Data.FileAttachment object. In below example, i am converting file to byte array using function and sending as attachment. You can write simple function which will convert file to byte array.

byte[] fileContent = FileToByteArray(fileName);
string Filename = “Yearly Report”;
string cid = Guid.NewGuid().ToString();

FileAttachment mAttachment = msg.Attachments.AddFileAttachment (Filename, fileContent);

This will add file in message objects attachment collection. You can add more than one file as an attachment.
In API there is an option to send inline attachment where link is created in message body. In case of inline attachment we need to specify unique contentId.

if (msgBody.Text.Contains("src=\"" + Filename + "\"")) {
msgBody.Text = msgBody.Text.Replace("src=\"" + Filename + "\"", "src=\"cid:" + cid + Filename;
mAttachment.IsInline = true;
mAttachment.ContentId = cid + Filename;
}
msg.Body = msgBody;

In some exchange server there is a limit to attachment size. If size of all attachments exceeds limit it will show an error.

  • Adding Recipients , BCC and CC to message
You can add one or more recipients, BCC (blind carbon copy) or CC (Carbon copy) to message. BCC and CC are optional

msg.ToRecipients.Add("Recipient1@mydomain.com");
msg.ToRecipients.Add("Recipient2@mydomain.com");
msg.BccRecipients.Add("BCCRecipient1@mydomain.com");
msg.CcRecipients.Add("CCRecipient1@mydomain.com");

In some exchange server there is maximum limit on recipient per message i.e. max no of recipients we can add as recipients. If no of recipient exceeds limit exchange server will show error. In this case you need to send multiple email messages with no of recipients less than or equal to set limit.

Sending messages

Once the service and message is configured final step is to send message. There are multiple methods available in EWS to save and send message.

  • msg.Save(WellKnownFolderName.Drafts)
You can save messages in Draft mailbox folder before sending. If Folder Name is not provided then it will take default folder name.

  • msg.Send()
This will send email message.

  • msg.SendAndSaveCopy(WellKnownFolderName.SentItems)
This method will send message and save copy by default to sentItems folder. You can also save copy to specific folder.

In summary, this blog will help you write code to configure email message with attachment and send request to Exchange Web Service using EWS Managed API. If you like this post share your feedback.

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.