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 = "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 关注
- 443 浏览
添加回答
举报