Monday, January 14, 2008 6:28 PM
Exchange 2007 EWS: Sending Email
Sending Email using Exchange 2007 Web Services (EWS) is a little trickier than I first anticipated (read: counterintuitive), since it uses the service.CreateItem() method call instead of the service.SendItem(). The basic idea is to formulate the email message as a CreateItemType with a MessageType assigned to the Item property, with the MessageDisposition set to "MessageDispositionType.SendAndSaveCopy." The following code shows an example of a library method that can send a basic email message with no attachments from a sender to a single recipient (it should be fairly easy to extrapolate multiple recipients, cc's & bcc's from there).
The first step with any EWS call is to set up your Exchange Service Binding:
ExchangeServiceBinding esb = new ExchangeServiceBinding();
esb.Credentials = new NetworkCredential(config.UserName, config.Password, config.Domain);
esb.Url = config.ServerURL;
Next, create the root MessageType that will serve as your email message:
MessageType emailMessage = new MessageType();
Now you can add the from/sender as a SingleRecipientType (there can't be multiple senders), and add the ToRecipients as an array of EmailAddressTypes. I'll also show the body and subject code since it is relatively straightforward.
//Add the sender/recipient to the email message
emailMessage.ToRecipients = new EmailAddressType;
emailMessage.ToRecipients = new EmailAddressType();
emailMessage.ToRecipients.EmailAddress = "firstname.lastname@example.org"; //Currently there is only one recipient
emailMessage.From = new SingleRecipientType(); //set up a single sender
emailMessage.From.Item = new EmailAddressType();
emailMessage.From.Item.EmailAddress = "email@example.com";
emailMessage.Subject = "Subject Goes Here";
emailMessage.Body = new BodyType();
emailMessage.Body.BodyType1 = BodyTypeType.Text; //specify HTML or plain Text
emailMessage.Body.Value = "Body Goes Here";
The next step is to place the email message inside of a CreateItemType object.
CreateItemType emailToSave = new CreateItemType();
emailToSave.Items = new NonEmptyArrayOfAllItemsType();
emailToSave.Items.Items = new ItemType;
emailToSave.Items.Items = emailMessage;
emailToSave.MessageDisposition = MessageDispositionType.SendAndSaveCopy;
emailToSave.MessageDispositionSpecified = true;
Finally, you call the CreateItem() method to create the item and send it off. I'll usually place this part in a try/catch block, and then return the ResponseCode (inside of the returned ResponseMessageType) so that it can be inspected for success.
CreateItemResponseType response = esb.CreateItem(emailToSave);
// Get the response messages.
ResponseMessageType rmta = response.ResponseMessages.Items;
Regardless of the complexities, it sure beats WebDAV!
Filed under: Code, ASP.NET, Exchange 2007