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

时间:2016-09-05 06:12:53

标签: php yii gmail-api

我正在使用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帐户中的所有电子邮件设置相同的电子邮件地址。

提前致谢!

2 个答案:

答案 0 :(得分:1)

您收到此错误:failedPrecondition: Unrecognized forwarding address,因为您尚未创建经过验证的转发地址。您需要先使用this API创建转发地址。然后,您的用户需要先验证该电子邮件地址,然后才能转发任何电子邮件。

这种方法的问题在于您需要此授权范围gmail.settings.sharing才能执行此操作,而这又需要域范围的授权。 See how to set it up here。如果您未设置此委派,则在尝试创建转发地址时会出现此错误:forbidden: Access restricted to service accounts that have been delegated domain-wide authority

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

  1. 设置域名授权
  2. 使用前创建转发地址(通过API)
  3. 希望这有帮助。

答案 1 :(得分:0)

这可能只是格式化错误,但请删除&#34; \&#34;字符,因为它可能会导致您遇到的错误。

如果您要将管理员帐户中的电子邮件转发到用户列表(全部),则可以使用ForwardingAddresses API。

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

快乐的编码!