Send e-mail with attachments using gmail rest api

2019-08-05 11:33发布

问题:

I am trying to send an e-mail with attachment using gmail api. This is my url request:

NSString *urlString = [NSString stringWithFormat:@"%@?access_token=%@&uploadType=multipart", @"apiURL", @"access_token"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"message" ofType:@"txt"];
NSString *myText = [NSString stringWithContentsOfFile:filePath];
[request setHTTPBody:[myText dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:@"multipart/related; boundary=foo_bar_baz" forHTTPHeaderField:@"Content-Type"];

//make request, etc....

and this is the content of message.txt file which contains json and attachment data.

POST /upload/gmail/v1/users/userId/messages/send?uploadType=multipart HTTP/1.1
Content-Type: multipart/related; boundary="foo_bar_baz"
Content-Length: 99999999999999999999999999

--foo_bar_baz
Content-Type: application/json; charset=UTF-8

{
"raw":"RnJvbTogSm9obiBEb2UgPGpkb2VAbWFjaGluZS5leGFtcGxlPiAKVG86IFRlc3QgTmFtZSA8Y2VtaWx0b2thdGxpQGNyZWF2ZXguY29tPiAKU3ViamVjdDogU2F5aW5nIEhlbGxvIApEYXRlOiBGcmksIDIxIE5vdiAxOTk3IDA5OjU1OjA2IC0wNjAwIAoKVGhpcyBpcyBhIG1lc3NhZ2UganVzdCB0byBzYXkgaGVsbG8uIFNvLCAiSGVsbG8i"

}

--foo_bar_baz
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="anothertest.jpg"
Content-Type: message/rfc822;

(image data)

--foo_bar_baz--

I can send message successfully but I can't see the attachment.

回答1:

I'm not that familiar with objective-c, but I did the same mistake in JavaScript a while back (Mail attachment wrong media type Gmail API)

You have to supply the ENTIRE mail in the raw-parameter before sending it. In your case it could be something like:

Content-Type: multipart/mixed; boundary="foo_bar_baz"
Content-Length: 99999999999999999999999999

--foo_bar_baz
Content-Type: text/plain; charset="UTF-8"

This is a message just to say hello. So, "Hello"

--foo_bar_baz
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="anothertest.jpg"
Content-Type: message/rfc822;

(image data)

--foo_bar_baz--

When you've constructed your mail like this, you have to urlSafe Base64-encode it and supply this encoded string as your raw-parameter!

$.ajax({
      type: "POST",
      url: "https://www.googleapis.com/gmail/v1/users/me/messages/send",
      contentType: "application/json",
      dataType: "json",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('Authorization','Bearer ' + accessToken);
      },
      data: JSON.stringify({"raw": mail}) //mail is the encoded mail above
    });