【发布时间】:2021-04-18 14:03:03
【问题描述】:
我是此 API 的新手,目前正在尝试通过 Gmail 发送电子邮件。我已经安装了 Laravel,并且 composer google/apiclient:"^2.7" 需要它。
这就是我如何调用创建消息和发送函数
$message = $this->googleApi->createMessage($user->name, $user->email, 'An email', $text);
$client = new Google_Client();
$service = new Google_Service_Gmail($client);
$userId = 'my-google-id.apps.googleusercontent.com'
$sendMessage = $this->googleApi->sendMessage($service, $userid, $message);
为 API 创建消息的类:
public function createMessage($sender, $to, $subject, $messageText)
{
$message = new Google_Service_Gmail_Message();
$subjectCharset = $charset = 'utf-8';
$messageBody = 'Hello';
$boundary = uniqid(rand(), true);
$rawMessageString = "From: <{$sender}>\r\n";
$rawMessageString .= "To: <{$to}>\r\n";
$rawMessageString .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($subject) . "?=\r\n";
$rawMessageString .= "MIME-Version: 1.0\r\n";
$rawMessageString .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
$rawMessageString .= "\r\n--{$boundary}\r\n";
$rawMessageString .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$rawMessageString .= "Content-Transfer-Encoding: base64" . "\r\n\r\n";
$rawMessageString .= str_replace("\n","",$messageBody)."\r\n";
$rawMessageString .= "--{$boundary}\r\n";
$rawMessage = rtrim(strtr(base64_encode($rawMessageString), '+/', '-_'), '=');
$message->setRaw($rawMessage);
return $message;
}
发送电子邮件的类:
public function sendMessage($service, $userId, $message)
{
try {
$request = $service->users_messages->send($userId, $message);
return $request;
} catch (Exception $e) {
return 'An error occurred: ' . $e->getMessage();
}
}
但由于某种原因,当我试图将其拉出时,它会响应
{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }
我有点卡住了。你能详细说明它想从我这里得到什么吗?提供了客户的 ID,但它说我不是未经身份验证的。
【问题讨论】:
标签: php laravel google-api gmail-api google-api-php-client