Send email messages by using EWS in Exchange

Learn how to send new or draft email messages, or to send a delayed email message by using the EWS Managed API or EWS in Exchange.

Whether you are using the EWS Managed API or EWS, you can send email messages in two ways. You can either send an existing message, such as a message stored in your Drafts folder, or you can create and send an email in one step. The methods and operations that you use to send the message are the same whether you're sending a message immediately, or sending a delayed message.

Table 1. EWS Managed API methods and EWS operations for sending email messages

Task EWS Managed API method EWS operation
Send a new email message
EmailMessage.SendAndSaveCopy
CreateItem
Send an existing email message
EmailMessage.Send
SendItem

Send a new email message by using the EWS Managed API

The following code example shows how to use the EmailMessage object to create an email message and the SendAndSaveCopy method to send the message to the recipient and save the message in the Sent Items folder.

This example assumes that service is a valid ExchangeService object and that the user has been authenticated to an Exchange server.

// Create an email message and provide it with connection 
// configuration information by using an ExchangeService object named service.
EmailMessage message = new EmailMessage(service);
// Set properties on the email message.
message.Subject = "Company Soccer Team";
message.Body = "Are you interested in joining?";
message.ToRecipients.Add("sadie@contoso.com");
// Send the email message and save a copy.
// This method call results in a CreateItem call to EWS.
message.SendAndSaveCopy();
Console.WriteLine("An email with the subject '" + message.Subject + "' has been sent to '" + message.ToRecipients[0] + "' and saved in the SendItems folder.");

Send a new email message by using EWS

The following code example shows how to use the CreateItem operation with a MessageDisposition value of SendAndSaveCopy to create an email message, send the message to the recipient, and save the message in the Sent Items folder. This is also the XML request that the EWS Managed API sends when you send a new email message.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
               xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" 
               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" 
               xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2007_SP1" />
  </soap:Header>
  <soap:Body>
    <m:CreateItem MessageDisposition="SendAndSaveCopy">
      <m:SavedItemFolderId>
        <t:DistinguishedFolderId Id="sentitems" />
      </m:SavedItemFolderId>
      <m:Items>
        <t:Message>
          <t:Subject>Company Soccer Team</t:Subject>
          <t:Body BodyType="HTML">Are you interested in joining?</t:Body>
          <t:ToRecipients>
            <t:Mailbox>
              <t:EmailAddress>sadie@contoso.com </t:EmailAddress>
              </t:Mailbox>
          </t:ToRecipients>
        </t:Message>
      </m:Items>
    </m:CreateItem>
  </soap:Body>
</soap:Envelope>

The server responds to the CreateItem request with a CreateItemResponse message that includes a ResponseCode value of NoError, which indicates that the email was created successfully, and the ItemId of the newly created message.

Send a draft email message by using the EWS Managed API

The following code example shows how to send a message that was stored in the Drafts folder, as shown in Create an email message by using the EWS Managed API. First, use the Bind method to retrieve the message, and then use the Send method to send the email message, as shown in the following code example. Note that this method does not save the sent message in the Sent Items folder.

In this case, the EmailMessageSchema.Subject and EmailMessageSchema.ToRecipients properties are added to the PropertySet so that the values can be included in the console output.

This example assumes that service is a valid ExchangeService object and that the user has been authenticated to an Exchange server.

// As a best practice, create a property set that limits the properties returned by the Bind method to only those that are required.
PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Subject, EmailMessageSchema.ToRecipients);
// This method call results in a GetItem call to EWS.
EmailMessage message = EmailMessage.Bind(service, ItemId, propSet);
// Send the email message.
// This method call results in a SendItem call to EWS.
message.Send();
Console.WriteLine("An email with the subject '" + message.Subject + "' has been sent to '" + message.ToRecipients[0] + "'.");

Send a draft email message by using EWS

The following code examples show how to send a message that was previously stored in the Drafts folder, as shown in Create an email message by using EWS. First use the GetItem operation to retrieve the email message to send. Then use the SendItem operation to send the email message to recipients and save it in the Sent Items folder.

The first message, the GetItem request message, specifies the ItemId of the draft email message to bind to, and elements in the ItemShape element limit the results to include in the GetItem response. The ItemShape element has a BaseShape of IdOnly, and the AdditionalProperties element includes the FieldURI values for the Subject property from the Item schema and the ToRecipients property from the Message schema, which means that only the ItemId, Subject, and ToRecipients elements will be returned to the client in the response. For more information about limiting the values returned in calls and the meaning of the BaseShape element, see Property sets and response shapes in EWS in Exchange.

This is also the XML request that is sent by the EWS Managed API when calling the Bind method. The values of some attributes and elements have been shortened for readability.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
               xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2007_SP1" />
  </soap:Header>
  <soap:Body>
    <m:GetItem>
      <m:ItemShape>
        <t:BaseShape>IdOnly</t:BaseShape>
        <t:AdditionalProperties>
          <t:FieldURI FieldURI="item:Subject" />
          <t:FieldURI FieldURI="message:ToRecipients" />
        </t:AdditionalProperties>
      </m:ItemShape>
      <m:ItemIds>
        <t:ItemId Id="AAMkADE4=" />
      </m:ItemIds>
    </m:GetItem>
  </soap:Body>
</soap:Envelope>

The following example shows the XML response that the server returns after it processes the GetItem operation. The response indicates that the email message was retrieved successfully, and includes the Subject and ToRecipient elements as requested. The values of some attributes and elements have been shortened for readability.

<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="https://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="15"
                         MinorVersion="0"
                         MajorBuildNumber="842"
                         MinorBuildNumber="10"
                         Version="V2_8"
                         xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
                         xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
                         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:GetItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
                       xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:GetItemResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Items>
            <t:Message>
              <t:ItemId Id="AAMkADE4="
                        ChangeKey="CQAAABYA" />
              <t:Subject>Project priorities</t:Subject>
              <t:ToRecipients>
                <t:Mailbox>
                  <t:Name>sadie@contoso.com</t:Name>
                  <t:EmailAddress>sadie@contoso.com</t:EmailAddress>
                  <t:RoutingType>SMTP</t:RoutingType>
                  <t:MailboxType>OneOff</t:MailboxType>
                </t:Mailbox>
              </t:ToRecipients>
            </t:Message>
          </m:Items>
        </m:GetItemResponseMessage>
      </m:ResponseMessages>
    </m:GetItemResponse>
  </s:Body>
</s:Envelope>

The second message, the SendItem request message, specifies the ItemId of the email message to send, as well as the SavedItemFolderId, which specifies the folder in which to save the sent item.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
               xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2007_SP1" />
  </soap:Header>
  <soap:Body>
    <m:SendItem SaveItemToFolder="true">
      <m:ItemIds>
        <t:ItemId Id="AAMkADE4="
                  ChangeKey="CQAAABYA" />
      </m:ItemIds>
      <m:SavedItemFolderId>
        <t:DistinguishedFolderId Id="sentitems" />
      </m:SavedItemFolderId>
    </m:SendItem>
  </soap:Body>
</soap:Envelope>

The server responds to the SendItem request with a SendItemResponse message that includes a ResponseCode value of NoError, which indicates that the email was sent successfully.

Send a delayed email message by using the EWS Managed API

The following code example shows how to use the EmailMessage object to create an email message, the ExtendedPropertyDefinition class to create a property definition for the PidTagDeferredSendTime (0x3FEF0040) property, and the SendAndSaveCopy method to send a delayed message and save the message in the Sent Items folder.

This example assumes that service is a valid ExchangeService object and that the user has been authenticated to an Exchange server.

// Create a new email message. 
EmailMessage message = new EmailMessage(service);
// Specify the email recipient and subject. 
message.ToRecipients.Add("sadie@contoso.com");
message.Subject = "Delayed email";
// Identify the extended property that can be used to specify when to send the email. 
ExtendedPropertyDefinition PidTagDeferredSendTime = new ExtendedPropertyDefinition(16367, MapiPropertyType.SystemTime);
// Set the time that will be used to specify when the email is sent. 
// In this example, the email will be sent one minute after the next line executes, 
// provided that the message.SendAndSaveCopy request is processed by the server within one minute. 
string sendTime = DateTime.Now.AddMinutes(1).ToUniversalTime().ToString();
// Specify when to send the email by setting the value of the extended property. 
message.SetExtendedProperty(PidTagDeferredSendTime, sendTime);
// Specify the email body. 
StringBuilder str = new StringBuilder();
str.AppendLine("The client submitted the SendAndSaveCopy request at: " + DateTime.Now.ToUniversalTime().ToString() + ".");
str.AppendLine("The email message will be sent at: " + sendTime + ".");
message.Body = str.ToString();
Console.WriteLine("");
Console.WriteLine("The client submitted the SendAndSaveCopy request at: " + DateTime.Now.ToUniversalTime().ToString() + ".");
Console.WriteLine("The email message will be sent at: " + sendTime + ".");
// Submit the request to send the email message. 
message.SendAndSaveCopy();

Send a delayed email message by using EWS

The following code example shows how to use the CreateItem operation with a MessageDisposition value of SendAndSaveCopy to create an email message, the ExtendedProperty element to create a property definition for the PidTagDeferredSendTime (0x3FEF0040) property to set a time to send the message, and the SavedItemFolderId element to save the sent message in the Sent Items folder.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
               xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange207_SP1" />
  </soap:Header>
  <soap:Body>
    <m:CreateItem MessageDisposition="SendAndSaveCopy">
      <m:SavedItemFolderId>
        <t:DistinguishedFolderId Id="sentitems" />
      </m:SavedItemFolderId>
      <m:Items>
        <t:Message>
          <t:Subject>Delayed email</t:Subject>
          <t:Body BodyType="HTML">
            The client submitted the SendAndSaveCopy request at: 1/2/2014 9:08:52 PM.
            The email message will be sent at: 1/2/2014 9:09:52 PM.
          </t:Body>
          <t:ExtendedProperty>
            <t:ExtendedFieldURI PropertyTag="16367"
                                PropertyType="SystemTime" />
            <t:Value>2014-01-02T21:09:52.000</t:Value>
          </t:ExtendedProperty>
          <t:ToRecipients>
            <t:Mailbox>
              <t:EmailAddress>sadie@contoso.com</t:EmailAddress>
            </t:Mailbox>
          </t:ToRecipients>
        </t:Message>
      </m:Items>
    </m:CreateItem>
  </soap:Body>
</soap:Envelope>

The server responds to the CreateItem request with a CreateItemResponse message that includes a ResponseCode value of NoError, which indicates that the email was created successfully, and the ItemId of the newly created message.

See also