1 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
開始編碼之前的要求。
獲取 Google Client Library(確保 php 在您的系統(tǒng)路徑中 > Install?Composer?> Install the library?
composer require google/apiclient:^2.0
)啟用 Gmail API(Google Developer console?> Library > Search 'Gmail API' > Enable(如果已啟用,您將看到管理按鈕)
創(chuàng)建服務(wù)帳戶(Google Developer console?> IAM & Admin > Service Accounts > 點(diǎn)擊“Create Service Account” > 像往常一樣填寫第 1 步 > 對(duì)于第 2 步,我將我的服務(wù)帳戶設(shè)置為項(xiàng)目所有者。 > 第 3 步我跳過了。)
創(chuàng)建一個(gè)密鑰(谷歌開發(fā)者控制臺(tái)> IAM 和管理 > 服務(wù)賬戶 > 點(diǎn)擊你新創(chuàng)建的服務(wù)賬戶的“操作”菜單 > 創(chuàng)建密鑰 > JSON > 將它存儲(chǔ)在你的代碼可以訪問的地方。)
設(shè)置全域委派(Google 管理員> 安全 > API 權(quán)限 > 一直向下滾動(dòng)以找到“管理全域委派” > 點(diǎn)擊“添加新” > 輸入在您剛剛下載的 json 文件中找到的客戶端 ID > 輸入在您需要的范圍內(nèi)。要通過 gmail 發(fā)送電子郵件,請(qǐng)查看此處的“授權(quán)”。)
啟用全域委派(Google Developer console?> IAM & Admin > Service Accounts > 單擊新創(chuàng)建的服務(wù)帳戶 > 單擊“編輯”> Show Domain-wide Delegation > Enable G-Suite Domain-wide Delegation)
如果您已遵循并完成了這些步驟,那么您就可以繼續(xù)執(zhí)行代碼部分了!
代碼本身。
<?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;
}
??>
- 1 回答
- 0 關(guān)注
- 527 瀏覽
添加回答
舉報(bào)