Gmail Api resumable upload Rest( attachment larger

2019-07-20 20:39发布

问题:

I am trying to send via Gmail Api Rest a mail with attachment larger than 5MB. To accomplish that I am trying to sent it with resumable upload. This is my code.

byte[] ba = System.IO.File.ReadAllBytes(uploadFromPath);
String base64String = Convert.ToBase64String(ba);
string url = "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=resumable"
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("X-Upload-Content-Type", "message/rfc822");
request.Headers["X-Upload-Content-Length"]= base64String.Length.ToString();
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = body.Length;

After I make the request I am getting the location

location = res.Headers["Location"];

and after that I make the PUT request with the location.

I would like to know what should I insert inside first request Body and what should be inside second request. I have seen this post Attaching a file using Resumable upload w/ Gmail API but the code worked only for files smaller than 5MB. Is there anything else I should do to accomplish attchment larger than 5MB?

回答1:

There's actually samples on the Upload Attachment docs.

Step 1: Start a resumable session Resumable session initiation request

POST /upload/gmail/v1/users/userId/messages/send?uploadType=resumable HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer your_auth_token
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: message/rfc822
X-Upload-Content-Length: 2000000

{
  "id": string,
  "threadId": string,
  "labelIds": [
    string
  ],
  "snippet": string,
  "historyId": unsigned long,
  "payload": {
    "partId": string,
    "mimeType": string,
    "filename": string,
    "headers": [
      {
        "name": string,
        "value": string
      }
    ],
    "body": users.messages.attachments Resource,
    "parts": [
      (MessagePart)
    ]
  },
  "sizeEstimate": integer,
  "raw": bytes
}

Step 2: Save the resumable session URI

HTTP/1.1 200 OK
Location: https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=resumable&upload_id=xa298sd_sdlkj2
Content-Length: 0

Step 3: Upload the file

PUT https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=resumable&upload_id=xa298sd_sdlkj2 HTTP/1.1
Content-Length: 2000000
Content-Type: message/rfc822

bytes 0-1999999