将大文件附加到 Outlook 邮件或事件Attach large files to Outlook messages or events

使用 Microsoft Graph API,可将最大 150 MB 的文件附加到 Outlook 邮件事件项目。Using the Microsoft Graph API, you can attach files up to 150 MB to an Outlook message or event item. 根据文件大小,选择以下两种方法之一来附加文件:Depending on the file size, choose one of two ways to attach the file:

  • 如果文件大小小于 3 MB,应该针对 Outlook 项的附件导航属性执行单个 POST;了解如何针对邮件事件执行此操作。If the file size is under 3 MB, do a single POST on the attachments navigation property of the Outlook item; see how to do this for a message or for an event. 成功的 POST 响应包括文件附件的 ID。The successful POST response includes the ID of the file attachment.
  • 如果文件大小介于 3MB 和 150MB 之间,则创建一个上传会话,并以迭代的方式使用 PUT 来上传文件的字节范围,直到完整的文件上传完毕。If the file size is between 3MB and 150MB, create an upload session, and iteratively use PUT to upload ranges of bytes of the file until you have uploaded the entire file. 最后一个成功 PUT 响应中的标头包括带附件 ID 的 URL。A header in the final successful PUT response includes a URL with the attachment ID.

若要将多个文件附加到邮件,请根据每个文件的文件大小,选择相应的方法,并单独附加文件。To attach multiple files to a message, choose the approach for each file based on its file size and attach the files individually.

本文逐步介绍了第二种方法,创建并使用上传会话来添加大型文件附件(大小超过 3 MB)至 Outlook 项。This article illustrates the second approach step by step, creating and using an upload session to add a large file attachment (of size over 3MB) to an Outlook item. 各步显示相应的邮件或事件代码。Each step shows the corresponding code for a message and for an event. 成功上传整个文件后,文章显示获取含有文件附件 ID 的响应标头,随后显示使用附件 ID 来获取原始附件内容或附件元数据。Upon successfully uploading the entire file, the article shows getting a response header that contains an ID for the file attachment, and then using that attachment ID to get the raw attachment content or attachment metadata.

重要

如果要将大文件附加到共享或委派邮箱中的邮件或事件,请注意一个已知问题Be aware of a known issue if you're attaching large files to a message or event in a shared or delegated mailbox.

第 1 步:创建上传会话Step 1: Create an upload session

创建上传会话,将文件附加到邮件或事件。Create an upload session to attach a file to a message or event. 在输入参数 AttachmentItem 中指定文件。Specify the file in the input parameter AttachmentItem.

成功的操作返回 HTTP 201 Created 和新的 uploadSession 实例,其中包含可在后续 PUT 操作中用于上传文件各部分的非跳转 URL。A successful operation returns HTTP 201 Created and a new uploadSession instance, which contains an opaque URL that you can use in subsequent PUT operations to upload portions of the file. uploadSession 提供一个临时存储位置,在此位置保存文件字节数,直到完整文件上传完毕。The uploadSession provides a temporary storage location where the bytes of the file are saved until you have uploaded the complete file.

请务必请求 Mail.ReadWrite 权限,以为邮件创建 uploadSession,并为事件创建 Calendars.ReadWriteMake sure to request Mail.ReadWrite permission to create the uploadSession for a message, and Calendars.ReadWrite for an event. 新的 uploadSessionuploadUrl 属性中返回的非跳转 URL 经过预身份验证,包含针对 https://outlook.office.com 域中后续 PUT 查询的相应授权令牌。The opaque URL, returned in the uploadUrl property of the new uploadSession, is pre-authenticated and contains the appropriate authorization token for subsequent PUT queries in the https://outlook.office.com domain. 该令牌会在 expirationDateTime 过期。That token expires by expirationDateTime. 请勿自定义 PUT 操作的此 URL。Do not customize this URL for the PUT operations.

响应中的 uploadSession 对象还包含 nextExpectedRanges 属性,这指示初始上传开始位置应该为 0 字节。The uploadSession object in the response also includes the nextExpectedRanges property, which indicates the initial upload starting location should be byte 0.

示例:创建邮件的上传会话Example: create an upload session for a message

请求Request

POST https://graph.microsoft.com/v1.0/me/messages/AAMkADI5MAAIT3drCAAA=/attachments/createUploadSession
Content-type: application/json

{
  "AttachmentItem": {
    "attachmentType": "file",
    "name": "flower",
    "size": 3483322
  }
}

响应Response

下列示例响应显示为邮件返回的 uploadSession 资源。The following example response shows the uploadSession resource returned for the message.

HTTP/1.1 201 Created
Content-type: application/json

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.uploadSession",
    "uploadUrl": "https://outlook.office.com/api/v2.0/Users('a8e8e219-4931-95c1-b73d-62626fd79c32@72aa88bf-76f0-494f-91ab-2d7cd730db47')/Messages('AAMkADI5MAAIT3drCAAA=')/AttachmentSessions('AAMkADI5MAAIT3k0tAAA=')?authtoken=eyJhbGciOiJSUzI1NiIsImtpZCI6IktmYUNIUlN6bllHMmNI",
    "expirationDateTime": "2019-09-25T01:09:30.7671707Z",
    "nextExpectedRanges": [
        "0-"
    ]
}

示例:创建事件的上传会话Example: create an upload session for an event

请求Request

POST https://graph.microsoft.com/v1.0/me/events/AAMkADU5CCmSAAA=/attachments/createUploadSession
Content-type: application/json

{
  "AttachmentItem": {
    "attachmentType": "file",
    "name": "flower",
    "size": 3483322
  }
}

响应Response

下列示例响应显示为shi'jian事件返回的 uploadSession 资源。The following example response shows the uploadSession resource returned for the event.

HTTP/1.1 201 Created
Content-type: application/json

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.uploadSession",
    "uploadUrl": "https://outlook.office.com/api/v2.0/Users('d3b9214b-dd8b-441d-b7dc-c446c9fa0e69@98a79ebe-74bf-4e07-a017-7b410848cb32')/Events('AAMkADU5CCmSAAA=')/AttachmentSessions('AAMkADU5RpAACJlCs8AAA=')?authtoken=eyJhbGciOiJSUzI1NiIsImtpZCI6IktmYUNIBtw",
    "expirationDateTime": "2020-02-22T02:46:56.7410786Z",
    "nextExpectedRanges": [
        "0-"
    ]
}

步骤 2:使用上传会话上传文件的字节范围Step 2: Use the upload session to upload a range of bytes of the file

如果要上传文件或文件的一部分,在 uploadSession 资源 uploadUrl 属性中,对第 1 步返回的 URL 进行 PUT 请求。To upload the file, or a portion of the file, make a PUT request to the URL returned in step 1 in the uploadUrl property of the uploadSession resource. 可上传整个文件,或将文件拆分为多个字节范围。You can upload the entire file, or split the file into multiple byte ranges. 为获得更好的性能,请保持每个字节范围小于 4 MB。For better performance, keep each byte range less than 4 MB.

按如下所述指定请求标头和请求正文。Specify request headers and request body as described below.

请求标头Request headers

名称Name 类型Type 说明Description
Content-LengthContent-Length Int32Int32 此操作中上传的字节数。The number of bytes being uploaded in this operation. 为获得更好的性能,请将每个 PUT 操作的字节数的上限限制为 4 MB。For better performance, keep the upper limit of the number of bytes for each PUT operation to 4 MB. 必填。Required.
Content-RangeContent-Range 字符串String 此操作中要上传的文件的从 0 开始的字节范围,格式为 bytes {start}-{end}/{total}The 0-based byte range of the file being uploaded in this operation, expressed in the format bytes {start}-{end}/{total}. 必填。Required.
Content-TypeContent-Type StringString MIME 类型。The MIME type. 指定 application/octet-streamSpecify application/octet-stream. 必填。Required.

请勿指定 Authorization 请求标头。Do not specify an Authorization request header. PUT 查询使用 uploadUrl 属性中预身份验证的 URL,该属性允许访问 https://outlook.office.com 域。The PUT query uses a pre-authenticated URL from the uploadUrl property, that allows access to the https://outlook.office.com domain.

请求正文Request body

指定要附加的文件的实际字节数,它们位于由 Content-Range 请求标头指定的位置范围内。Specify the actual bytes of the file to be attached, that are in the location range specified by the Content-Range request header.

响应Response

成功的上传将返回 HTTP 200 OKuploadSession 对象。A successful upload returns HTTP 200 OK and an uploadSession object. 请注意响应对象中的以下项:Note the following in the response object:

  • ExpirationDateTime 属性指示 uploadUrl 属性值中嵌入的身份验证令牌的到期日期/时间。The ExpirationDateTime property indicates the expiration date/time for the auth token embedded in the uploadUrl property value. 此到期日期/时间与步骤 1 中由初始 uploadSession 返回的值相同。This expiration date/time remains the same as returned by the initial uploadSession in step 1.
  • NextExpectedRanges 指定上传开始的下一个字节位置,例如 "NextExpectedRanges":["2097152"]The NextExpectedRanges specifies the next byte location to start uploading from, for example, "NextExpectedRanges":["2097152"]. 必须按顺序上传文件中的字节。You must upload bytes in a file in order.
  • uploadUrl 属性不会显式返回,因为上传会话的所有 PUT 操作使用创建会话时返回的同一 URL(步骤 1)。The uploadUrl property is not explicitly returned, because all PUT operations of an upload session use the same URL returned when creating the session (step 1).

示例:首先上传至消息Example: first upload to the message

请求Request

PUT https://outlook.office.com/api/v2.0/Users('a8e8e219-4931-95c1-b73d-62626fd79c32@72aa88bf-76f0-494f-91ab-2d7cd730db47')/Messages('AAMkADI5MAAIT3drCAAA=')/AttachmentSessions('AAMkADI5MAAIT3k0tAAA=')?authtoken=eyJhbGciOiJSUzI1NiIsImtpZCI6IktmYUNIUlN6bllHMmNI
Content-Type: application/octet-stream
Content-Length: 2097152
Content-Range: bytes 0-2097151/3483322

{
  <bytes 0-2097151 of the file to be attached, in binary format>
}

响应Response

下列示例响应在 NextExpectedRanges 属性中显示服务器预期的下一字节范围的起点。The following example response shows in the NextExpectedRanges property the start of the next byte range that the server expects.

HTTP/1.1 200 OK
Content-type: application/json

{
  "@odata.context":"https://outlook.office.com/api/v2.0/$metadata#Users('a8e8e219-4931-95c1-b73d-62626fd79c32%4072aa88bf-76f0-494f-91ab-2d7cd730db47')/Messages('AAMkADI5MAAIT3drCAAA%3D')/AttachmentSessions/$entity",
  "ExpirationDateTime":"2019-09-25T01:09:30.7671707Z",
  "NextExpectedRanges":["2097152"]
}

示例:首先上传至事件Example: first upload to the event

请求Request

PUT https://outlook.office.com/api/v2.0/Users('d3b9214b-dd8b-441d-b7dc-c446c9fa0e69@98a79ebe-74bf-4e07-a017-7b410848cb32')/Events('AAMkADU5CCmSAAA=')/AttachmentSessions('AAMkADU5RpAACJlCs8AAA=')?authtoken=eyJhbGciOiJSUzI1NiIsImtpZCI6IktmYUNIBtw
Content-Type: application/octet-stream
Content-Length: 2097152
Content-Range: bytes 0-2097151/3483322

{
  <bytes 0-2097151 of the file to be attached, in binary format>
}

响应Response

下列示例响应在 NextExpectedRanges 属性中显示服务器预期的下一字节范围的起点。The following example response shows in the NextExpectedRanges property the start of the next byte range that the server expects.

HTTP/1.1 200 OK
Content-type: application/json

{
    "@odata.context":"https://outlook.office.com/api/v2.0/$metadata#Users('d3b9214b-dd8b-441d-b7dc-c446c9fa0e69%4098a79ebe-74bf-4e07-a017-7b410848cb32')/Events('AAMkADU5CCmSAAA%3D')/AttachmentSessions/$entity",
    "ExpirationDateTime":"2020-02-22T02:46:56.7410786Z",
    "NextExpectedRanges":["2097152"]
}

步骤 3:继续上传字节范围,直至完整文件上传完毕Step 3: Continue uploading byte ranges until the entire file has been uploaded

执行步骤 2 中的初始上传后,在会话的到期日期/时间前,使用步骤 2 中所述的 PUT 请求,继续上传文件中剩余的部分。Following the initial upload in step 2, continue to upload the remaining portion of the file, using a similar PUT request as described in step 2, before you reach the expiration date/time for the session. 使用 NextExpectedRanges 集合确定要上传的下一个字节范围的开头。Use the NextExpectedRanges collection to determine where to start the next byte range to upload. 可能会发现指定了多个范围,这些范围指明了服务器尚未收到的文件部分。You may see multiple ranges specified, indicating parts of the file that the server has not yet received. 如果需要恢复中断的传输,并且客户端不能确定服务的状态,这个方法很有用。This is useful if you need to resume a transfer that was interrupted and your client is unsure of the state on the service.

成功上传文件的最后一个字节后,最终 PUT 操作返回 HTTP 201 Created 以及指示 https://outlook.office.com 域中文件附件 URL 的 Location 标头。Once the last byte of the file has been successfully uploaded, the final PUT operation returns HTTP 201 Created and a Location header that indicates the URL to the file attachment in the https://outlook.office.com domain. 可从 URL 获取附件 ID 并将其保存供以后使用。You can get the attachment ID from the URL and save it for later use. 可以使用该 ID 获取附件的元数据,或使用 Microsoft Graph 终结点将附件从 Outlook 项中删除,具体取决于你的场景。Depending on your scenario, you can use that ID to get the metadata of the attachment, or remove the attachment from the Outlook item using the Microsoft Graph endpoint.

下列示例显示在此处理步骤中上传最后的文件字节范围至邮件和事件。The following examples show uploading the last byte range of the file to the message and to the event in the preceding steps.

示例:最后上传至消息Example: final upload to the message

请求Request

PUT https://outlook.office.com/api/v2.0/Users('a8e8e219-4931-95c1-b73d-62626fd79c32@72aa88bf-76f0-494f-91ab-2d7cd730db47')/Messages('AAMkADI5MAAIT3drCAAA=')/AttachmentSessions('AAMkADI5MAAIT3k0tAAA=')?authtoken=eyJhbGciOiJSUzI1NiIsImtpZCI6IktmYUNIUlN6bllHMmNI
Content-Type: application/octet-stream
Content-Length: 1386170
Content-Range: bytes 2097152-3483321/3483322

{
  <bytes 2097152-3483321 of the file to be attached, in binary format>
}

响应Response

下列示例显示可保存附件 ID(AAMkADI5MAAIT3drCAAABEgAQANAqbAe7qaROhYdTnUQwXm0=)以供随后使用的 Location 响应标头。The following example response shows a Location response header from which you can save the attachment ID (AAMkADI5MAAIT3drCAAABEgAQANAqbAe7qaROhYdTnUQwXm0=) for later use.

HTTP/1.1 201 Created

Location: https://outlook.office.com/api/v2.0/Users('a8e8e219-4931-95c1-b73d-62626fd79c32@72aa88bf-76f0-494f-91ab-2d7cd730db47')/Messages('AAMkADI5MAAIT3drCAAA=')/Attachments('AAMkADI5MAAIT3drCAAABEgAQANAqbAe7qaROhYdTnUQwXm0=')
Content-Length: 0

示例:最后上传至事件Example: final upload to the event

请求Request

PUT https://outlook.office.com/api/v2.0/Users('d3b9214b-dd8b-441d-b7dc-c446c9fa0e69@98a79ebe-74bf-4e07-a017-7b410848cb32')/Events('AAMkADU5CCmSAAA=')/AttachmentSessions('AAMkADU5RpAACJlCs8AAA=')?authtoken=eyJhbGciOiJSUzI1NiIsImtpZCI6IktmYUNIBtw
Content-Type: application/octet-stream
Content-Length: 1386170
Content-Range: bytes 2097152-3483321/3483322

{
  <bytes 2097152-3483321 of the file to be attached, in binary format>
}

响应Response

下列示例显示可保存附件 ID(AAMkADU5CCmSAAANZAlYPeyQByv7Y=)以供随后使用的 Location 响应标头。The following example response shows a Location response header from which you can save the attachment ID (AAMkADU5CCmSAAANZAlYPeyQByv7Y=) for later use.

HTTP/1.1 201 Created

Location: https://outlook.office.com/api/v2.0/Users('d3b9214b-dd8b-441d-b7dc-c446c9fa0e69@98a79ebe-74bf-4e07-a017-7b410848cb32')/Events('AAMkADU5CCmSAAA=')/Attachments('AAMkADU5CCmSAAANZAlYPeyQByv7Y=')
Content-Length: 0

步骤 4(可选):从 Outlook 项中获取文件附件Step 4 (optional): Get the file attachment from the Outlook item

和往常一样,从 Outlook 项中获取附件在理论上并不受附件大小限制。As always, getting an attachment from an Outlook item is not technically limited by attachment size.

但是,获取采用 base64 编码格式的大文件附件会影响 API 性能。However, getting a large file attachment in base64-encoded format affects API performance. 如果需要大型附件:If you expect a large attachment:

示例:获取附加到事件的原始文件Example: Get the raw file attached to the event

按照事件示例和使用上一步 Location 标头中返回的附件 ID,下一示例请求显示使用 $value 参数获取附件的原始内容数据。Following the event example and using the attachment ID returned in the Location header of the previous step, the next example request shows using a $value parameter to get the attachment raw content data.

请求Request

GET https://graph.microsoft.com/v1.0/Users('d3b9214b-dd8b-441d-b7dc-c446c9fa0e69@98a79ebe-74bf-4e07-a017-7b410848cb32')/Events('AAMkADU5CCmSAAA=')/Attachments('AAMkADU5CCmSAAANZAlYPeyQByv7Y=')/$value

响应Response

HTTP/1.1 200 OK
content-length: 3483322
Content-type: image/jpeg

{Raw bytes of the file}

示例:获取邮件附加的文件的元数据Example: Get the metadata of the file attached to the message

按照邮件示例,下一示例请求显示使用 $select 参数来获取有关邮件的文件附件的部分元数据,不包括 contentBytesFollowing the message example, the next example request shows using a $select parameter to get some of the metadata of a file attachment on a message, excluding contentBytes.

请求Request

GET https://graph.microsoft.com/api/v1.0/Users('a8e8e219-4931-95c1-b73d-62626fd79c32@72aa88bf-76f0-494f-91ab-2d7cd730db47')/Messages('AAMkADI5MAAIT3drCAAA=')/Attachments('AAMkADI5MAAIT3drCAAABEgAQANAqbAe7qaROhYdTnUQwXm0=')?$select=lastModifiedDateTime,name,contentType,size,isInline

响应Response

HTTP/1.1 200 OK
Content-type: application/json

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('a8e8e219-4931-95c1-b73d-62626fd79c32%4072aa88bf-76f0-494f-91ab-2d7cd730db47')/messages('AAMkADI5MAAIT3drCAAA%3D')/attachments/$entity",
    "@odata.type": "#microsoft.graph.fileAttachment",
    "@odata.mediaContentType": "image/jpeg",
    "id": "AAMkADI5MAAIT3drCAAABEgAQANAqbAe7qaROhYdTnUQwXm0=",
    "lastModifiedDateTime": "2019-09-24T23:27:43Z",
    "name": "flower",
    "contentType": "image/jpeg",
    "size": 3640066,
    "isInline": false
}

替代方法:取消上传会话Alternative: Cancel the upload session

在上传会话到期之前的任何时间,如果必须取消上传,可使用同一初始非跳转 URL 来删除上传会话。At any point of time before the upload session expires, if you have to cancel the upload, you can use the same initial opaque URL to delete the upload session. 成功的操作将返回 HTTP 204 No ContentA successful operation returns HTTP 204 No Content.

示例:取消邮件的上传会话Example: cancel the upload session for the message

请求Request

DELETE https://outlook.office.com/api/v2.0/Users('a8e8e219-4931-95c1-b73d-62626fd79c32@72aa88bf-76f0-494f-91ab-2d7cd730db47')/Messages('AAMkADI5MAAIT3drCAAA=')/AttachmentSessions('AAMkADI5MAAIT3k0tAAA=')?authtoken=eyJhbGciOiJSUzI1NiIsImtpZCI6IktmYUNIUlN6bllHMmNI

响应Response

HTTP/1.1 204 No content

错误Errors

ErrorAttachmentSizeShouldNotBeLessThanMinimumSizeErrorAttachmentSizeShouldNotBeLessThanMinimumSize

尝试创建上传会话以附加小于 3 MB 的文件时返回此错误。This error is returned when attempting to create an upload session to attach a file smaller than 3 MB. 如果文件大小小于 3 MB,则应该针对邮件事件附件导航属性执行单个 POST。If the file size is under 3 MB, you should do a single POST on the attachments navigation property of the message or of the event. 成功的 POST 响应包括附加到邮件的文件的 ID。The successful POST response includes the ID of the file attached to the message.