使用GMail API (PHP)为所有用户设置转发地址


Setting up forwarding address for all users using GMail API (PHP)

我正在为一个内部应用程序使用Gmail API。我需要为所有使用管理员帐户的用户设置传入和传出电子邮件的电子邮件转发。我在Yii中使用Google PHP API客户端库。

我在看这篇文章。https://developers.google.com/identity/protocols/OAuth2ServiceAccount

下面就是我要做的。

define('JSON_FILE', '/path/to/json/file');
$user_to_impersonate = '<My domain wide authorized admin email address>';
$scopes = [ 'Google_Service_Gmail::GMAIL_SETTINGS_SHARING,'Google_Service_Gmail::MAIL_GOOGLE_COM];
$google_client = new 'Google_Client();
$google_client->setAuthConfig(CLIENT_SECRET_PATH);
$google_client->setScopes($scopes);
$google_client->setSubject($user_to_impersonate);
$google_client->setIncludeGrantedScopes(true);
// setup the forwarding address
$service = new 'Google_Service_Gmail($google_client);
$f = new 'Google_Service_Gmail_AutoForwarding();
$f->setEnabled(TRUE);
$f->setEmailAddress('<my forwarding email address>');
$f->setDisposition("leaveInInbox");
$service->users_settings->updateAutoForwarding('me',$f)

我得到以下错误,

Unrecognized forwarding address

我知道有些事情是不对的:)。有人可以让我知道你的专家回应来解决这个问题,并得到这个工作。我觉得我正在尝试为我正在使用的电子邮件地址设置转发,但不是所有用户。但是我想为组织Gmail帐户中的所有电子邮件设置相同的电子邮件地址。

提前感谢!

您得到这个错误:failedPrecondition: Unrecognized forwarding address,因为您还没有创建一个经过验证的转发地址。您需要首先使用此API创建一个转发地址。然后,您的用户需要验证该电子邮件地址,然后才能将任何电子邮件转发给它。

此方法的问题在于,您需要此授权范围gmail.settings.sharing才能执行此操作,这反过来又需要域范围的权限委托。看看如何在这里设置。如果您没有设置此委托,您将在尝试创建转发地址时得到此错误:forbidden: Access restricted to service accounts that have been delegated domain-wide authority

所以你需要执行两个步骤:

  1. 设置权限域委派
  2. 在使用前创建一个转发地址(通过API)

这可能只是一个格式错误,但请删除"'"字符,因为它可能会导致您遇到的错误。

如果您想将电子邮件转发到和从管理帐户到用户列表(所有),您可以使用ForwardingAddresses API。

请注意,消息只能转发到已注册和验证的电子邮件地址。这可能是您得到错误的原因。在调用updateAutoForwarding之前创建一个forwardingAddress,希望它能正常工作。

编码快乐!