在 Exchange 中使用 EWS 以代理的形式访问电子邮件Access email as a delegate by using EWS in Exchange

了解如何通过使用 Exchange 中的 EWS 托管 API 或 EWS,将电子邮件作为代理访问。Learn how to access email as a delegate by using the EWS Managed API or EWS in Exchange.

您可以使用 EWS 托管 API 或 EWS 为用户委派对邮箱所有者的 "收件箱" 文件夹的访问权限。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. 主要区别在于,必须使用显式访问来查找或创建电子邮件项目,然后在确定项目 ID 之后,可以使用隐式访问来获取、更新或删除项目。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.

表1。用于将电子邮件作为代理访问的 EWS 托管 API 方法和 EWS 操作Table 1. EWS Managed API methods and EWS operations for accessing email as a delegate

如果您想要 .。。If you want to… 使用此 EWS 托管 API 方法 .。。Use this EWS Managed API method… 使用此 EWS 操作 .。。Use this EWS operation…
创建电子邮件并将其作为代理发送Create and send an email as a delegate
EmailMessageFolderId参数提供对邮箱所有者的 "草稿" 文件夹的显式访问权限EmailMessage.Save where the FolderId parameter provides explicit access to the mailbox owner's Drafts folder
FolderId参数提供对邮箱所有者的 "已发送邮件" 文件夹的显式访问SendAndSaveCopy EmailMessageEmailMessage.SendAndSaveCopy where the FolderId parameter provides explicit access to the mailbox owner's Sent Items folder
CreateItem其中邮箱元素指定邮箱所有者的EmailAddressCreateItem where the Mailbox element specifies the EmailAddress of the mailbox owner
SendItem其中邮箱元素指定邮箱所有者的EmailAddressSendItem where the Mailbox element specifies the EmailAddress of the mailbox owner
创建多封电子邮件作为代理Create multiple email messages as a delegate
FolderId参数提供对邮箱所有者的 "收件箱" 文件夹的显式访问权限CreateItems ExchangeServiceExchangeService.CreateItems where the FolderId parameter provides explicit access to the mailbox owner's Inbox folder
CreateItem其中邮箱元素指定邮箱所有者的EmailAddressCreateItem where the Mailbox element specifies the EmailAddress of the mailbox owner
搜索电子邮件或查找作为代理的电子邮件Search for or find an email as a delegate
FolderId参数提供对邮箱所有者的 "收件箱" 文件夹的显式访问权限FindItems ExchangeServiceExchangeService.FindItems where the FolderId parameter provides explicit access to the mailbox owner's Inbox folder
FindItem其中邮箱元素指定邮箱所有者的EmailAddressFindItem where the Mailbox element specifies the EmailAddress of the mailbox owner
将电子邮件作为代理获取Get an email as a delegate
EmailMessage.BindEmailMessage.Bind
GetItemGetItem
将电子邮件更新为代理Update an email as a delegate
EmailMessage后接EmailMessageEmailMessage.Bind followed by EmailMessage.Update
GetItem后接UpdateItemGetItem followed by UpdateItem
删除作为代理的电子邮件Delete an email as a delegate
EmailMessage后接EmailMessageEmailMessage.Bind followed by EmailMessage.Delete
GetItem后接DeleteItemGetItem 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 ."

备注

在本文的代码示例中,primary@contoso.com 是邮箱所有者。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.

使用 EWS 托管 API 创建电子邮件并将其作为代理发送Create and send an email as a delegate by using the EWS Managed API

使用 EWS 托管 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. 本示例演示如何使用save方法将邮件保存到邮箱所有者的 "草稿" 文件夹中,然后使用SendAndSaveCopy方法将邮件保存到邮箱所有者的 "已发送邮件" 文件夹中,并将其保存到邮箱所有者的 "已发送邮件" 文件夹中。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.

本示例假定服务是代理的有效ExchangeService对象,并且已为委派授予对邮箱所有者的 "收件箱"、"草稿" 和 "已发送邮件" 文件夹的适当权限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.");
}

使用 EWS 创建电子邮件并将其作为代理发送Create and send an email as a delegate by using EWS

EWS 使您可以使用代理用户的服务对象代表邮箱所有者创建和发送电子邮件。EWS enables you to use the service object for the delegate user to create and send email on behalf of the mailbox owner. 本示例演示如何使用CreateItem操作创建电子邮件和SendItem操作,以发送时间并将其保存在邮箱所有者的 "已发送邮件" 文件夹中。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.

这也是在使用Save方法创建和发送电子邮件时,EWS 托管 API 发送的第一个 XML 请求。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="https://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="https://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>

服务器使用CreateItemResponse邮件响应CreateItem请求,其中包含ResponseCode元素值NoError,表示已成功创建并保存了该电子邮件。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. 该响应还包含新创建的电子邮件的项目 ID。The response also contains the item ID of the newly created email.

为了提高可读性, ItemId值已缩短。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="https://schemas.microsoft.com/exchange/services/2006/types"
                         xmlns="https://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="https://schemas.microsoft.com/exchange/services/2006/messages"
                          xmlns:t="https://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>

接下来,使用SendItem操作代表邮箱所有者发送邮件,并将其保存在邮箱所有者的 "已发送邮件" 文件夹中。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.

为了提高可读性, ItemId值已缩短。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="https://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="https://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>

服务器使用SendItemResponse邮件响应SendItem请求,其中包含ResponseCode元素值NoError,表示电子邮件已成功发送并保存到邮箱所有者的 "已发送邮件" 文件夹。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="https://schemas.microsoft.com/exchange/services/2006/types"
                         xmlns="https://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="https://schemas.microsoft.com/exchange/services/2006/messages"
                        xmlns:t="https://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>

使用 EWS 托管 API 搜索作为代理的电子邮件Search for an email as a delegate by using the EWS Managed API

若要搜索电子邮件,您必须使用包含FolderId参数的 FindItems 方法之一,以便您可以指定邮箱所有者的 "收件箱" 文件夹ExchangeServiceTo 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);
    }
}

FindItems调用返回带有 ID 的响应后,您可以使用 id 和隐式访问来获取、更新或删除该电子邮件,而无需指定邮箱所有者的 SMTP 地址。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.

使用 EWS 搜索作为代理的电子邮件Search for an email as a delegate by using EWS

通过 EWS,您可以使用代理用户的服务对象搜索符合一组搜索条件的电子邮件。EWS enables you to use the service object for the delegate user to search for emails that meet a set of search criteria. 本示例演示如何使用FindItem操作查找所有者的 "收件箱" 文件夹中包含主题中包含 "足球" 一词的邮件。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.

这也是在搜索电子邮件时,EWS 托管 API 发送的 XML 请求。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="https://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="https://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>

服务器使用FindItemResponse邮件响应FindItem请求,其中包含ResponseCode元素值NoError,表示已成功完成搜索。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. 响应包含符合搜索条件的任何电子邮件的Message元素。The response contains a Message element for any emails that met the search criteria. 在这种情况下,仅找到一个电子邮件。In this case, only one email is found.

为了提高可读性, ItemId元素的值已缩短。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="https://schemas.microsoft.com/exchange/services/2006/types"
                         xmlns="https://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="https://schemas.microsoft.com/exchange/services/2006/messages"
                        xmlns:t="https://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>

现在您已拥有满足条件的电子邮件的ItemId ,您可以通过使用ItemId隐式访问来获取、更新或删除该电子邮件,而无需指定邮箱所有者的 SMTP 地址。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.

使用 EWS 托管 API 获取、更新或删除作为委派的电子邮件项目Get, update, or delete email items as a delegate by using the EWS Managed API

您可以使用 EWS 托管 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. 唯一的区别是ExchangeService对象是代表委派用户的。The only difference is that the ExchangeService object is for the delegate user. Bind方法调用中包含的项目 ID 在邮箱所有者的 "收件箱" 文件夹中唯一标识邮箱存储中的项目。The item ID included in the Bind method call uniquely identifies the item in the mailbox store, in the mailbox owner's Inbox folder.

表2。将电子邮件作为代理使用的 EWS 托管 API 方法Table 2. EWS Managed API methods working with email as a delegate

任务Task EWS 托管的 API 方法EWS Managed API method 代码示例Code example
获取电子邮件Get an email
绑定Bind
使用 EWS 托管 API 获取项Get an item by using the EWS Managed API
更新电子邮件Update an email
绑定后接更新Bind followed by Update
使用 EWS 托管 API 更新项Update an item by using the EWS Managed API
删除电子邮件Delete an email
绑定后接删除Bind followed by Delete
使用 EWS 托管 API 删除项Delete an item by using the EWS Managed API

使用 EWS 获取、更新或删除作为代理的电子邮件项目Get, update, or delete email items as a delegate by using EWS

您可以使用 EWS 托管 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 service object is for the delegate user. GetItem请求中包含的项目 ID 在邮箱所有者的 "收件箱" 文件夹中唯一标识邮箱存储中的项目。The item ID included in the GetItem request uniquely identifies the item in the mailbox store, in the mailbox owner's Inbox folder.

表3。将电子邮件作为代理使用的 EWS 操作Table 3. EWS operations for working with email as a delegate

任务Task EWS 操作EWS operation 代码示例Code example
获取电子邮件Get an email
GetItemGetItem
使用 EWS 获取项Get an item by using EWS
更新电子邮件Update an email
GetItem后接UpdateItemGetItem followed by UpdateItem
使用 EWS 更新项Update an item by using EWS
删除电子邮件Delete an email
GetItem后接DeleteItemGetItem followed by DeleteItem
使用 EWS 删除项Delete an item by using EWS

另请参阅See also