如何使用 php 中的 google gmail api 和 cURL 发送电子邮件?

Adr*_*ien 3 php curl sendmail gmail-api

我在 Php 和 cURL 中使用 Google Api 发送邮件时遇到问题,

我尝试过这个:

// 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);
Run Code Online (Sandbox Code Playgroud)

但我收到这样的错误消息:

{“error”:{“errors”:[{“domain”:“global”,“reason”:“badContent”,“message”:“不支持媒体类型“application/json”。有效媒体类型:[message /rfc822]" } ], "code": 400, "message": "不支持媒体类型“application/json”。有效媒体类型:[message/rfc822]" } }

当我尝试使用:

'Content-Type: message/rfc822';
Run Code Online (Sandbox Code Playgroud)

我有一条新的错误消息:

{ "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "需要收件人地址" } ], "code": 400, "message": “需要收件人地址”} }

我不想使用谷歌提供的库。

Pat*_*ert 7

看起来您正在发送 JSON 编码数据,而您应该尊重message/rfc822format

您可能不应该对您的消息进行 base64 编码 + json 编码:

<?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);
Run Code Online (Sandbox Code Playgroud)