簡體   English   中英

Gmail API - PHP - 使用 email 服務帳戶發送

[英]Gmail API - PHP - Sending email using service account

問題:我遇到了 HTTP 400 錯誤,指出“前提條件檢查失敗”。 每當我調用 sendMessage() 方法時。

我不知道我有什么可以考慮:

  1. 啟用 Gmail API。
  2. 創建了一個服務帳戶。
  3. 設置域范圍的委派(針對 G-Suites)。
  4. 為服務啟用域范圍的委派。

作為說明,我已經成功運行 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', 'some@email.com', 'This is but a test', 'Please work...');

// Email a user
sendMessage($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();
  }
}
?>

任何幫助是極大的贊賞!

我為此聯系了 Google 支持,他們已經解決了我的問題!

以下是支持人員在 email 中告訴我的內容: “您必須在代碼上模擬用戶才能使用服務帳戶調用 Gmail API。” 所以“前提條件檢查失敗”。 錯誤是由未正確驗證引起的。

因此,為了完整起見,我將運行您必須通過 go 才能讓您的代碼工作的過程。 請注意,您將需要三樣東西:G-Suites、訪問 Google 開發者控制台和訪問 G-Suites 管理控制台。

開始編碼之前的要求。

  1. 獲取 Google 客戶端庫(確保 php 在您的系統路徑中 > 安裝Composer > 安裝庫composer require google/apiclient:^2.0
  2. 啟用 Gmail API (谷歌開發者控制台>庫>搜索'Gmail API'>啟用(如果已經啟用,你會看到管理按鈕)
  3. 創建服務帳戶( Google Developer console > IAM & Admin > Service Accounts > 點擊“創建服務帳戶”> 照常填寫第 1 步 > 第 2 步,我將我的服務帳戶設置為項目所有者。> 第 3 步我跳過了。)
  4. 創建一個密鑰( Google Developer console > IAM & Admin > Service Accounts > 單擊新創建的服務帳戶的“操作”菜單 > 創建密鑰 > JSON > 將其存儲在您的代碼可以訪問的位置。)
  5. 設置域范圍委派(谷歌管理員>安全> API權限>一直向下滾動以找到“管理域范圍委派”>單擊“添加新”>輸入您剛剛下載的json文件中的客戶端ID>輸入在您需要的范圍內。要通過 gmail 發送電子郵件, 請查看此處的“授權” 。)
  6. 啟用域范圍委派(谷歌開發者控制台> IAM & Admin > 服務帳戶> 點擊新創建的服務帳戶> 點擊“編輯”> 顯示域范圍委派> 啟用 G-Suite 域范圍委派)

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

代碼本身。

<?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 = "your@domain.com";

$sender = $user_to_impersonate;
$to = 'another@domain.com';
$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;
}
 ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM