亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Gmail API - PHP - 使用服務帳戶發送電子郵件

Gmail API - PHP - 使用服務帳戶發送電子郵件

PHP
烙印99 2023-05-12 16:11:36
問題:我一直遇到 HTTP 400 錯誤,指出“先決條件檢查失敗”。每當我調用 sendMessage() 方法時。我不知道我有什么可以考慮的:啟用 Gmail API。創建了一個服務帳戶。設置全域委派(針對 G-Suites)。為服務啟用域范圍的委派。請注意,我已成功運行 quickstart.php,因此我知道谷歌庫已正確安裝。下面是我的代碼:<?php require_once('../../vendor/autoload.php');$client = new Google_Client();$credentials_file = '../../vendor/google/auth/credentials.json';$client->setAuthConfig($credentials_file);$client->setApplicationName("no-reply mailing");$client->setScopes(['https://www.googleapis.com/auth/gmail.send']);$service = new Google_Service_Gmail($client);$message = createMessage('me', '[email protected]', 'This is but a test', 'Please work...');// Email a usersendMessage($service, 'me', $message);/*** @param $sender string sender email address* @param $to string recipient email address* @param $subject string email subject* @param $messageText string email text* @return Google_Service_Gmail_Message*/function createMessage($sender, $to, $subject, $messageText) { $message = new Google_Service_Gmail_Message(); $rawMessageString = "From: <{$sender}>\r\n"; $rawMessageString .= "To: <{$to}>\r\n"; $rawMessageString .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n"; $rawMessageString .= "MIME-Version: 1.0\r\n"; $rawMessageString .= "Content-Type: text/html; charset=utf-8\r\n"; $rawMessageString .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n"; $rawMessageString .= "{$messageText}\r\n"; $rawMessage = strtr(base64_encode($rawMessageString), array('+' => '-', '/' => '_')); $message->setRaw($rawMessage); return $message;}function sendMessage($service, $userId, $message) {  try {    $message = $service->users_messages->send($userId, $message);    print 'Message with ID: ' . $message->getId() . ' sent.';    return $message;  } catch (Exception $e) {    print 'An error occurred: ' . $e->getMessage();  }}?>任何幫助是極大的贊賞!
查看完整描述

1 回答

?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

開始編碼之前的要求。

  1. 獲取 Google Client Library(確保 php 在您的系統路徑中 > Install?Composer?> Install the library?composer require google/apiclient:^2.0

  2. 啟用 Gmail API(Google Developer console?> Library > Search 'Gmail API' > Enable(如果已啟用,您將看到管理按鈕)

  3. 創建服務帳戶(Google Developer console?> IAM & Admin > Service Accounts > 點擊“Create Service Account” > 像往常一樣填寫第 1 步 > 對于第 2 步,我將我的服務帳戶設置為項目所有者。 > 第 3 步我跳過了。)

  4. 創建一個密鑰(谷歌開發者控制臺> IAM 和管理 > 服務賬戶 > 點擊你新創建的服務賬戶的“操作”菜單 > 創建密鑰 > JSON > 將它存儲在你的代碼可以訪問的地方。)

  5. 設置全域委派(Google 管理員> 安全 > API 權限 > 一直向下滾動以找到“管理全域委派” > 點擊“添加新” > 輸入在您剛剛下載的 json 文件中找到的客戶端 ID > 輸入在您需要的范圍內。要通過 gmail 發送電子郵件,請查看此處的“授權”。)

  6. 啟用全域委派(Google Developer console?> IAM & Admin > Service Accounts > 單擊新創建的服務帳戶 > 單擊“編輯”> Show Domain-wide Delegation > Enable G-Suite Domain-wide Delegation)

如果您已遵循并完成了這些步驟,那么您就可以繼續執行代碼部分了!

代碼本身。

<?php

// Library obtained from https://developers.google.com/gmail/api/quickstart/php

require_once('../../vendor/autoload.php');


// Some user within your G-Suites domain

$user_to_impersonate = "[email protected]";


$sender = $user_to_impersonate;

$to = '[email protected]';

$subject = 'The subject of an email.';

$messageText = 'Finally this works!';


// The path to your service account credentials goes here.

putenv("GOOGLE_APPLICATION_CREDENTIALS=credentials.json");

$client = new Google_Client();

$client->useApplicationDefaultCredentials();

$client->setSubject($sender);

$client->setApplicationName("Quickstart");

$client->setScopes(["https://mail.google.com/",

? ? ? ? ? ? ? ? ? ? "https://www.googleapis.com/auth/gmail.compose",

? ? ? ? ? ? ? ? ? ? "https://www.googleapis.com/auth/gmail.modify",

? ? ? ? ? ? ? ? ? ? "https://www.googleapis.com/auth/gmail.send"]);

$service = new Google_Service_Gmail($client);


// Main Process

try {

? $msg = createMessage($sender, $to, $subject, $messageText);

? sendMessage($service, $sender, $msg);

} catch (Exception $e) {

? print "An error occurred: " . $e->getMessage();

}


function sendMessage($service, $sender, $msg) {

? $service->users_messages->send($sender, $msg);

}


function createMessage($sender, $to, $subject, $messageText) {

? $rawMsgStr = "From: <{$sender}>\r\n";

? $rawMsgStr .= "To: <{$to}>\r\n";

? $rawMsgStr .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n";

? $rawMsgStr .= "MIME-Version: 1.0\r\n";

? $rawMsgStr .= "Content-Type: text/html; charset=utf-8\r\n";

? $rawMsgStr .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";

? $rawMsgStr .= "{$messageText}\r\n";


? // The message needs to be encoded in Base64URL

? $mime = rtrim(strtr(base64_encode($rawMsgStr), '+/', '-_'), '=');

? $msg = new Google_Service_Gmail_Message();

? $msg->setRaw($mime);

? return $msg;

}

??>


查看完整回答
反對 回復 2023-05-12
  • 1 回答
  • 0 關注
  • 529 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號