Bewerken

Delen via


Access email as a delegate by using EWS in Exchange

Learn how to access email as a delegate by using the EWS Managed API or EWS in Exchange.

You can use the EWS Managed API or EWS to give a user delegate access to a mailbox owner's Inbox folder. The delegate can then create meeting requests on behalf of the mailbox owner, search for email, and retrieve, update, and delete email from the mailbox owner's Inbox folder, depending on their permissions.

As a delegate, you use the same methods and operations to access a mailbox owner's Inbox folder that you use to access an Inbox folder without delegate access. The main difference is that you have to use explicit access to find or create an email item, and then after you identify the item ID, you can use implicit access to get, update, or delete the item.

Table 1. EWS Managed API methods and EWS operations for accessing email as a delegate

If you want to… Use this EWS Managed API method… Use this EWS operation…
Create and send an email as a delegate
EmailMessage.Save where the FolderId parameter provides explicit access to the mailbox owner's Drafts folder
EmailMessage.SendAndSaveCopy where the FolderId parameter provides explicit access to the mailbox owner's Sent Items folder
CreateItem where the Mailbox element specifies the EmailAddress of the mailbox owner
SendItem where the Mailbox element specifies the EmailAddress of the mailbox owner
Create multiple email messages as a delegate
ExchangeService.CreateItems where the FolderId parameter provides explicit access to the mailbox owner's Inbox folder
CreateItem where the Mailbox element specifies the EmailAddress of the mailbox owner
Search for or find an email as a delegate
ExchangeService.FindItems where the FolderId parameter provides explicit access to the mailbox owner's Inbox folder
FindItem where the Mailbox element specifies the EmailAddress of the mailbox owner
Get an email as a delegate
EmailMessage.Bind
GetItem
Update an email as a delegate
EmailMessage.Bind followed by EmailMessage.Update
GetItem followed by UpdateItem
Delete an email as a delegate
EmailMessage.Bind followed by EmailMessage.Delete
GetItem followed by DeleteItem

Keep the following things in mind when working with emails as a delegate:

  • If a delegate only needs to work with meeting requests and responses, the delegate does not need access to the Inbox folder. For more information, see prerequisite tasks for accessing calendars as a delegate.

  • When a recipient receives a message that was sent on behalf of a mailbox owner, the sender appears as "Delegate on behalf of mailbox owner."

Note

In the code examples in this article, primary@contoso.com is the mailbox owner.

Prerequisite tasks

Before a user can access the mailbox owner's Inbox folder as a delegate, the user must be added as a delegate with permissions to the mailbox owner's Inbox folder.

Create and send an email as a delegate by using the EWS Managed API

The EWS Managed API enables you to use the service object for the delegate user to create and send email on behalf of the mailbox owner. This example shows how to use the Save method to save the message in the mailbox owner's Drafts folder, and then the SendAndSaveCopy method to send the mail and save the message in the mailbox owner's Sent Items folder.

This example assumes that service is a valid ExchangeService object for the delegate and that the delegate has been granted the appropriate permissions for the mailbox owner's Inbox, Drafts, and Sent Items folder.

public static void DelegateAccessCreateEmail(ExchangeService service)
{
    // 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");
    // Save the email to the mailbox owner's Drafts folder.
    // This method call results in a CreateItem call to EWS.
    // The FolderId parameter contains the context for the 
    // mailbox owner's Inbox folder. Any additional actions 
    // taken on this message will be performed in the mailbox 
    // owner's mailbox. 
    message.Save(new FolderId(WellKnownFolderName.Drafts, new Mailbox("primary@contoso.com")));
    // Send the email and save the message in the mailbox owner's 
    // Sent Items folder.
    // This method call results in a SendItem call to EWS.
    message.SendAndSaveCopy(new FolderId(WellKnownFolderName.SentItems, new Mailbox("primary@contoso.com")));
    Console.WriteLine("An email with the subject '" + message.Subject + "' has been sent to '" 
    + message.ToRecipients[0] + "' and saved in the Sent Items folder of the mailbox owner.");
}

Create and send an email as a delegate by using EWS

EWS enables you to use the service object for the delegate user to create and send email on behalf of the mailbox owner. This example shows how to use the CreateItem operation to create an email and the SendItem operation to send the time and save it in the mailbox owner's Sent Items folder.

This is also the first XML request that the EWS Managed API sends when you use the Save method to create and send an email.

<?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="SaveOnly">
      <m:SavedItemFolderId>
        <t:DistinguishedFolderId Id="drafts">
          <t:Mailbox>
            <t:EmailAddress>primary@contoso.com</t:EmailAddress>
          </t:Mailbox>
        </t:DistinguishedFolderId>
      </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 element value of NoError, which indicates that the email was created and saved successfully. The response also contains the item ID of the newly created email.

The ItemId value has 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="893"
                         MinorBuildNumber="17"
                         Version="V2_10"
                         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>
    <m:CreateItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
                          xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:CreateItemResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Items>
            <t:Message>
              <t:ItemId Id="iNRaAAA="
                        ChangeKey="CQAAABYAAADOilbYa8KaT7ZgMoTz2P+hAAABiQPU" />
            </t:Message>
          </m:Items>
        </m:CreateItemResponseMessage>
      </m:ResponseMessages>
    </m:CreateItemResponse>
  </s:Body>
</s:Envelope>

Next, use the SendItem operation to send the message on behalf of the mailbox owner and save it in the mailbox owner's Sent Items folder.

The ItemId value has 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:SendItem SaveItemToFolder="true">
      <m:ItemIds>
        <t:ItemId Id="iNRaAAA="
                  ChangeKey="CQAAABYAAADOilbYa8KaT7ZgMoTz2P+hAAABiQPU" />
      </m:ItemIds>
      <m:SavedItemFolderId>
        <t:DistinguishedFolderId Id="sentitems">
          <t:Mailbox>
            <t:EmailAddress>primary@contoso.com</t:EmailAddress>
          </t:Mailbox>
        </t:DistinguishedFolderId>
      </m:SavedItemFolderId>
    </m:SendItem>
  </soap:Body>
</soap:Envelope>

The server responds to the SendItem request with a SendItemResponse message that includes a ResponseCode element value of NoError, which indicates that the email was sent and saved to the mailbox owner's Sent Items folder successfully.

<?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="893"
                         MinorBuildNumber="17"
                         Version="V2_10"
                         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>
    <m:SendItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
                        xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:SendItemResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
        </m:SendItemResponseMessage>
      </m:ResponseMessages>
    </m:SendItemResponse>
  </s:Body>
</s:Envelope>

Search for an email as a delegate by using the EWS Managed API

To search for an email, you must use one of the ExchangeService.FindItems methods that includes a FolderId parameter, so that you can specify the mailbox owner's Inbox folder.

static void DelegateAccessSearchEmailWithFilter(ExchangeService service)
{
    // Limit the result set to 10 items.
    ItemView view = new ItemView(10);
    // Define the search filter.
    SearchFilter.ContainsSubstring filter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, 
        "soccer", ContainmentMode.Substring, ComparisonMode.IgnoreCase);
    view.PropertySet = new PropertySet(ItemSchema.Subject,
                                       ItemSchema.DateTimeReceived,
                                       EmailMessageSchema.IsRead);
    // Item searches do not support deep traversal.
    view.Traversal = ItemTraversal.Shallow;
    // Sorting.
    view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
    try
    {
        // Call FindItems to find matching Inbox items. 
        // The parameters of FindItems must denote the mailbox owner,
        // mailbox, and Inbox folder.
        // This call results in a FindItem call to EWS.
        FindItemsResults<Item> results = service.FindItems(new 
            FolderId(WellKnownFolderName.Inbox, "primary@contoso.com"), 
            filter, view);
        foreach (Item item in results.Items)
        {
            Console.WriteLine("Subject: {0}", item.Subject);
            Console.WriteLine("Id: {0}", item.Id.ToString());
            if (item is EmailMessage)
            {
                EmailMessage message = item as EmailMessage;
                Console.WriteLine("Read: {0}", message.IsRead.ToString());
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception while enumerating results: {0}", ex.Message);
    }
}

After the FindItems call returns a response with an ID, you can get, update or delete that email by using the ID and implicit access - and you do not need to specify the mailbox owner's SMTP address.

Search for an email as a delegate by using EWS

EWS enables you to use the service object for the delegate user to search for emails that meet a set of search criteria. This example shows how to use the FindItem operation to find messages in the owner's Inbox folder that contain the word "soccer" in the subject.

This is also the XML request that the EWS Managed API sends when you search for an email.

<?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:FindItem Traversal="Shallow">
      <m:ItemShape>
        <t:BaseShape>IdOnly</t:BaseShape>
        <t:AdditionalProperties>
          <t:FieldURI FieldURI="item:Subject" />
          <t:FieldURI FieldURI="item:DateTimeReceived" />
          <t:FieldURI FieldURI="message:IsRead" />
        </t:AdditionalProperties>
      </m:ItemShape>
      <m:IndexedPageItemView MaxEntriesReturned="10"
                             Offset="0"
                             BasePoint="Beginning" />
      <m:Restriction>
        <t:Contains ContainmentMode="Substring"
                    ContainmentComparison="IgnoreCase">
          <t:FieldURI FieldURI="item:Subject" />
          <t:Constant Value="soccer" />
        </t:Contains>
      </m:Restriction>
      <m:SortOrder>
        <t:FieldOrder Order="Descending">
          <t:FieldURI FieldURI="item:DateTimeReceived" />
        </t:FieldOrder>
      </m:SortOrder>
      <m:ParentFolderIds>
        <t:DistinguishedFolderId Id="inbox">
          <t:Mailbox>
            <t:EmailAddress>primary@contoso.com</t:EmailAddress>
          </t:Mailbox>
        </t:DistinguishedFolderId>
      </m:ParentFolderIds>
    </m:FindItem>
  </soap:Body>
</soap:Envelope>

The server responds to the FindItem request with a FindItemResponse message that includes a ResponseCode element value of NoError, which indicates that the search completed successfully. The response contains a Message element for any emails that met the search criteria. In this case, only one email is found.

The value of the ItemId element has 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="893"
                         MinorBuildNumber="17"
                         Version="V2_10"
                         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>
    <m:FindItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
                        xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:FindItemResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:RootFolder IndexedPagingOffset="1"
                        TotalItemsInView="1"
                        IncludesLastItemInRange="true">
            <t:Items>
              <t:Message>
                <t:ItemId Id="iNwoAAA="
                          ChangeKey="CQAAABYAAADOilbYa8KaT7ZgMoTz2P+hAAABiQuu" />
                <t:Subject>Soccer team</t:Subject>
                <t:DateTimeReceived>2014-03-10T06:16:55Z</t:DateTimeReceived>
                <t:IsRead>false</t:IsRead>
              </t:Message>
            </t:Items>
          </m:RootFolder>
        </m:FindItemResponseMessage>
      </m:ResponseMessages>
    </m:FindItemResponse>
  </s:Body>
</s:Envelope>

Now that you have the ItemId for the email that meets your criteria, you can get, update, or delete that email by using the ItemId and implicit access - and you do not need to specify the mailbox owner's SMTP address.

Get, update, or delete email items as a delegate by using the EWS Managed API

You can use the EWS Managed API to get, update, or delete an email in the same way that you perform these actions when you're not using delegate access. The only difference is that the ExchangeService object is for the delegate user. The item ID included in the Bind method call uniquely identifies the item in the mailbox store, in the mailbox owner's Inbox folder.

Table 2. EWS Managed API methods working with email as a delegate

Task EWS Managed API method Code example
Get an email
Bind
Get an item by using the EWS Managed API
Update an email
Bind followed by Update
Update an item by using the EWS Managed API
Delete an email
Bind followed by Delete
Delete an item by using the EWS Managed API

Get, update, or delete email items as a delegate by using EWS

You can use the EWS Managed API to get, update, or delete an email in the same way that you perform these actions when you're not using delegate access. The only difference is that the service object is for the delegate user. The item ID included in the GetItem request uniquely identifies the item in the mailbox store, in the mailbox owner's Inbox folder.

Table 3. EWS operations for working with email as a delegate

Task EWS operation Code example
Get an email
GetItem
Get an item by using EWS
Update an email
GetItem followed by UpdateItem
Update an item by using EWS
Delete an email
GetItem followed by DeleteItem
Delete an item by using EWS

See also