【问题标题】:How to send an email, using google gmail api in php with cURL?如何使用带有 cURL 的 php 中的 google gmail api 发送电子邮件?
【发布时间】:2020-06-01 05:04:03
【问题描述】:

我在 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": "不支持媒体类型 'application/json'。有效的媒体类型: [message/rfc822]" } ], "code": 400, "message": "不支持媒体类型'application/json'。有效媒体类型:[message/rfc822]" } }

当我尝试使用时:

'Content-Type: message/rfc822';

我有一条新的错误信息:

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

我不想使用 google 提供的库。

【问题讨论】:

标签: php curl gmail-api sendmail


【解决方案1】:

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

您可能不应该 base64-encode + json-encode 您的消息:

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

【讨论】:

  • 我试过你的方法,效果很好。非常感谢您的帮助!
猜你喜欢
  • 2014-09-16
  • 2017-04-14
  • 2014-08-27
  • 2014-10-30
  • 2019-04-17
  • 2017-05-25
  • 2018-08-20
  • 1970-01-01
  • 2016-09-22
相关资源
最近更新 更多