3

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

I tried this one:

// ENVOIE EMAIL

$message="To: [email protected]\r\nFrom: [email protected]\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.

2

1 Answer 1

7

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: [email protected]\r\nFrom: [email protected]\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);
Sign up to request clarification or add additional context in comments.

1 Comment

I tried with your method, and it works wonderfully. Thank you very much for your help !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.