Gmail API PHP客户端库或api - 如何发送gmail草稿?

时间:2016-08-10 06:41:25

标签: php google-api-php-client google-client

我要求在预定时间发送草稿电子邮件(Gmail)。 我试过下面的代码。

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

我在卷曲发布后得到的结果如下

数组([id] => r-5083530165761240787)但未设置草稿(电子邮件)。

1 个答案:

答案 0 :(得分:1)

您需要进行以下两项更改 更改1:在第3行,您需要替换

   Content-Type: message/rfc822 to Content-Type: application/json

更改2:在第38行,您需要替换

   $raw .= "id: $to ".$line.$line; to $raw = '{ "id": "'.$t.'" }'.$line.$line;

说明:数据必须以原始格式传递,内容类型为json。

发送草稿时,您可以选择按原样或更新消息发送消息。如果要使用新消息更新草稿内容,请在drafts.send请求的正文中提供草稿资源;设定要发送的草案草案;并将draft.message.raw字段设置为编码为base64url编码字符串的新MIME消息。有关更多信息,请参阅drafts.send。

参考:https://developers.google.com/gmail/api/guides/drafts