Reputation: 436
I got requirement to send drafted email(Gmail) on scheduled time. I tried below code.
$access_token = 'ya29.DxswidlwadllsidVeg5B67CdpLN6QR0d1nCuQmg9GaMT9iq8-zIA8O29yR9rEMM';
//the access token is subject to change every hour
$header = array('Content-Type: message/rfc822', "Authorization: Bearer $access_token");
$to = '125699645855239833'; // this is a draft id.
$line = "\r\n";
$raw='';
$url = 'https://www.googleapis.com/upload/gmail/v1/users/me/drafts?fields=id&key=XsqwwosqldwwdssaOLwotWD6seRloXZM';
$raw .= "id: $to ".$line.$line;
$method_type = 1; // set as post method
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HEADER, 0);
if( $header !== 0 ){
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
}
if( $method_type == 1 or $method_type == 0 ){
curl_setopt($curl, CURLOPT_POST, $method_type);
}else{
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
}
if( $data !== 0 ){
curl_setopt($curl, CURLOPT_POSTFIELDS, $raw);
}
$response = curl_exec($curl);
$json = json_decode($response, true);
print_r($json);
curl_close($curl);
I got result after curl posting as below
Array ( [id] => r-5083530165761240787 ) but draft(Email) was not set.
Upvotes: 1
Views: 341
Reputation: 141
You need two changes as following Change 1: at line no.3, You need replace
Content-Type: message/rfc822 to Content-Type: application/json
Change 2: at line no.38, You need replace
$raw .= "id: $to ".$line.$line; to $raw = '{ "id": "'.$t.'" }'.$line.$line;
Explain: data has to be passed in raw format with content type json.
When sending a draft, you can choose to send the message as-is or as with an updated message. If you are updating the draft content with a new message, supply a Draft resource in the body of the drafts.send request; set the draft.id of the draft to be sent; and set the draft.message.raw field to the new MIME message encoded as a base64url encoded string. For more information, see drafts.send.
Reference: https://developers.google.com/gmail/api/guides/drafts
Upvotes: 1