简体   繁体   中英

How to send an email, using google gmail api in php with cURL?

I have a problem sending mail using the Google Api in Php and cURL,

I tried this one:

// ENVOIE EMAIL

$message="To: test@example.com\r\nFrom: test@example.com\r\nSubject: GMail test.\r\n My message";
$email=base64_encode($message);

$url_email = 'https://www.googleapis.com/upload/gmail/v1/users/me/messages/send';

$curlPost = array(
    'raw' => $email,
);
$ch = curl_init();      
curl_setopt($ch, CURLOPT_URL, $url_email);      
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);      
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $AccessToken, 'Accept: application/json','Content-Type: application/json'));    
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = curl_exec($ch);
// $data = json_decode(curl_exec($ch), true);;
curl_close($ch);
echo '<br/><h2>Send email</h2>';
print_r($data);

But I get an error message like this :

{ "error": { "errors": [ { "domain": "global", "reason": "badContent", "message": "Media type 'application/json' is not supported. Valid media types: [message/rfc822]" } ], "code": 400, "message": "Media type 'application/json' is not supported. Valid media types: [message/rfc822]" } }

And when I tried with :

'Content-Type: message/rfc822';

I have a new error message :

{ "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "Recipient address required" } ], "code": 400, "message": "Recipient address required" } }

I do not want to use the library offered by google.

Looks like you are sending JSON encoded data while you should respect message/rfc822 format .

You should probably not base64-encode + json-encode your message:

<?php
$message = "To: test@example.com\r\nFrom: test@example.com\r\nSubject: GMail test.\r\n My message";


$ch = curl_init('https://www.googleapis.com/upload/gmail/v1/users/me/messages/send'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $AccessToken", 'Accept: application/json', 'Content-Type: message/rfc822'));    
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$data = curl_exec($ch);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM