1 回答

TA貢獻1906條經驗 獲得超10個贊
開始編碼之前的要求。
獲取 Google Client Library(確保 php 在您的系統路徑中 > Install?Composer?> Install the library?
composer require google/apiclient:^2.0
)啟用 Gmail API(Google Developer console?> Library > Search 'Gmail API' > Enable(如果已啟用,您將看到管理按鈕)
創建服務帳戶(Google Developer console?> IAM & Admin > Service Accounts > 點擊“Create Service Account” > 像往常一樣填寫第 1 步 > 對于第 2 步,我將我的服務帳戶設置為項目所有者。 > 第 3 步我跳過了。)
創建一個密鑰(谷歌開發者控制臺> IAM 和管理 > 服務賬戶 > 點擊你新創建的服務賬戶的“操作”菜單 > 創建密鑰 > JSON > 將它存儲在你的代碼可以訪問的地方。)
設置全域委派(Google 管理員> 安全 > API 權限 > 一直向下滾動以找到“管理全域委派” > 點擊“添加新” > 輸入在您剛剛下載的 json 文件中找到的客戶端 ID > 輸入在您需要的范圍內。要通過 gmail 發送電子郵件,請查看此處的“授權”。)
啟用全域委派(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;
}
??>
- 1 回答
- 0 關注
- 529 瀏覽
添加回答
舉報