Reputation: 11
I'm working with the Gmail API for an internal application. I need to set email forwarding for both incoming and outgoing emails for all the users using the admin account. I'm using the Google PHP API client library in Yii.
I'm following this article. https://developers.google.com/identity/protocols/OAuth2ServiceAccount
Following is what I'm trying to do.
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)
I get the following error,
Unrecognized forwarding address
I know that something is not correct :). Can someone please let me know your expert response to fix this and get this working. I feel that i'm trying to set the forwarding for the email address I'm using but not for all the users. But I want to set the same email address for all the emails in the organisation Gmail account.
Thanks in advance!
Upvotes: 0
Views: 1827
Reputation: 196
You get this error: failedPrecondition: Unrecognized forwarding address
because you have not yet created a verified forwarding address. You need to create a forwarding address first using this API. Then your user needs to verify that email address before you can forward any emails to it.
The problem with this approach is that you need this authorization scope gmail.settings.sharing
in order to do it, which in turn needs Domain-wide Delegation of Authority. See how to set it up here. If you do not setup this delegation you will get this error when trying to create a forwarding address: forbidden: Access restricted to service accounts that have been delegated domain-wide authority
.
So you need to perform 2 steps:
Hope this helps.
Upvotes: 4
Reputation: 2998
It may just be a formatting error, but please remove the "\" characters as it may contribute to the error you're encountering.
If you want to forward emails to and from the admin account to a list of users (all), you can use ForwardingAddresses
API for that.
Do note that messages can only be forwarded to registered and verified email addresses. This may be reason why you're getting the error. Create a forwardingAddress before you call the updateAutoForwarding
, and hopefully it will work our right.
Happy coding!
Upvotes: 0