I'm currently trying to test the new Gmail REST API.
In the API Explorer it is possible to authorize requests using OAuth 2.0 and to execute a request, i.e. send a message.
First I authorized.
I'm using the following test data (and of course I used a valid to
email address):
{
"raw": "c2VuZGluZyBhIG1haWwgdXNpbmcgR21haWwgUkVTVCBBUEk=",
"payload": {
"headers": [
{ "name": "to", "value": "info@something.com" },
{ "name": "from", "value": "taifunbaer@gmail.com" },
{ "name": "subject", "value": "Test Gmail REST API" }
],
"mimeType": "text/plain"
}
}
I also get a 200 OK
and the following result back, which looks fine.
{
"id": "146dee391881b35b",
"threadId": "146dee391881b35b",
}
However, the mail will not be sent successfully and I can find an message from nobody@gmail.com
in the inbox instead;: "An error occurred, your message has not been sent."
Questions:
1. Did someone test this successfully?
2. Do I have to add some other parameter to get this running?
EDIT: There are 2 different HTTP request methods,
- the Upload URI for media upload requests, and
- the Metadata URI for metadata-only requests
The API Explorer currently supports metadata requests only
, which means plain-text messages without attachment, and this is what I'm trying to do.
got it!
after reading the RFC 2822 specification I found out, that the complete message needs to be passed in the
raw
parameter, see the example:So after base64 encoding the complete message, passing it in the
raw
parameter without using any other parameter, it works fine.Edit 1:
As @Amit mentioned, it must be web-safe base64 encoded, see also https://code.google.com/p/stringencoders/wiki/WebSafeBase64
To only convert
+
to-
and/
to_
was sufficient for me.Edit 2:
To answer the question of @Hjulle here an example: you only need the
userId
and in the request body theraw
parameter. Let's assume, your email address isjdoe@machine.example
First Base64 encode the complete message (see above) using an online encoder and you get this string:
Now convert
+
to-
and/
to_
and you getNow pass this in the
raw
parameter of the API Explorer.Note: This is a PHP specific answer, but I'm sure some of you will find it useful.
In case you're struggling with setting up the raw data correctly in PHP as I did, using PHPMailer would make things cleaner and easier for you.
After including the library in your code (if you use composer, just add "phpmailer/phpmailer": "~5.2" in the require section of your composer.json), you set the basic details:
Now you can base64 encode the $mime to get the raw string for the Gmail API. Use this instead of simple base64_encode, in order to get a valid web safe encoded string.
rtrim(strtr(base64_encode($mime), '+/', '-_'), '=');