使用gmail rest api -objective-c发送带附件的电子邮件

时间:2015-02-16 00:10:25

标签: objective-c nsurlconnection gmail-api

我正在尝试使用gmail api发送带附件的电子邮件。 这是我的网址请求:

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....

这是包含json和附件数据的message.txt文件的内容。

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--

我可以成功发送消息,但我看不到附件。

enter image description here

1 个答案:

答案 0 :(得分:1)

我对objective-c并不熟悉,但我在JavaScript中犯了同样的错误(Mail attachment wrong media type Gmail API

在发送之前,您必须在raw-parameter中提供ENTIRE邮件。在你的情况下,它可能是这样的:

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--

如果您构建了这样的邮件,则必须对其进行urlSafe Base64编码并将此编码字符串作为原始参数提供!

$.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
    });