gpt4 book ai didi

php - 如何在带有 cURL 的 php 中使用 google gmail api 发送电子邮件?

转载 作者:行者123 更新时间:2023-12-04 10:34:22 25 4
gpt4 key购买 nike

我在 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);

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

{ "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]" } }

当我尝试:

'Content-Type: message/rfc822';

我有一条新的错误信息:

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

我不想使用 google 提供的库。

最佳答案

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

你可能不应该对你的消息进行 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);

关于php - 如何在带有 cURL 的 php 中使用 google gmail api 发送电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60259497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com