Stay organized with collections
Save and categorize content based on your preferences.
You can use Settings to
configure forwarding for an account. To be used as a forwarding email address,
an address must fulfill one of the following criteria:
You must create
forwarding addresses prior to use. In some cases, users must also verify ownership of the
address as well.
If Gmail requires user verification for a forwarding address, the address is returned with the
status pending. A verification message is automatically sent to the
target email address. The owner of the email address must complete the verification
process before it can be used.
Forwarding addresses that do not require verification have a verification status of accepted.
Enabling auto-forwarding
Call the updateAutoForwarding
method to enable auto-forwarding for an account. The call requires both a registered
and verified forwarding address as well as an action to take on forwarded messages.
For example, to enable auto-forwarding and move forwarded messages to the trash:
importcom.google.api.client.googleapis.json.GoogleJsonError;importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.gmail.Gmail;importcom.google.api.services.gmail.GmailScopes;importcom.google.api.services.gmail.model.AutoForwarding;importcom.google.api.services.gmail.model.ForwardingAddress;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;/* Class to demonstrate the use of Gmail Enable Forwarding API */publicclassEnableForwarding{/** * Enable the auto-forwarding for an account. * * @param forwardingEmail - Email address of the recipient whose email will be forwarded. * @return forwarding id and metadata, {@code null} otherwise. * @throws IOException - if service account credentials file not found. */publicstaticAutoForwardingenableAutoForwarding(StringforwardingEmail)throwsIOException{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(GmailScopes.GMAIL_SETTINGS_SHARING);HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Create the gmail API clientGmailservice=newGmail.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Gmail samples").build();try{// Enable auto-forwarding and move forwarded messages to the trashForwardingAddressaddress=newForwardingAddress().setForwardingEmail(forwardingEmail);ForwardingAddresscreateAddressResult=service.users().settings().forwardingAddresses().create("me",address).execute();if(createAddressResult.getVerificationStatus().equals("accepted")){AutoForwardingautoForwarding=newAutoForwarding().setEnabled(true).setEmailAddress(address.getForwardingEmail()).setDisposition("trash");autoForwarding=service.users().settings().updateAutoForwarding("me",autoForwarding).execute();System.out.println(autoForwarding.toPrettyString());returnautoForwarding;}}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelyGoogleJsonErrorerror=e.getDetails();if(error.getCode()==403){System.err.println("Unable to enable forwarding: "+e.getDetails());}else{throwe;}}returnnull;}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefenable_forwarding():"""Enable email forwarding. Returns:Draft object, including forwarding id and result meta data. Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """creds,_=google.auth.default()try:# create gmail api clientservice=build("gmail","v1",credentials=creds)address={"forwardingEmail":"gduser1@workspacesamples.dev"}# pylint: disable=E1101result=(service.users().settings().forwardingAddresses().create(userId="me",body=address).execute())ifresult.get("verificationStatus")=="accepted":body={"emailAddress":result.get("forwardingEmail"),"enabled":True,"disposition":"trash",}# pylint: disable=E1101result=(service.users().settings().updateAutoForwarding(userId="me",body=body).execute())print(f"Forwarding is enabled : {result}")exceptHttpErroraserror:print(f"An error occurred: {error}")result=Nonereturnresultif__name__=="__main__":enable_forwarding()
To disable autoforwarding, call updateAutoForwarding
and set the enabled property to false.
Forwarding specific messages
Auto-forwarding sends all received messages to the target account. To
selectively forward messages, use filters
to create rules that forward in response to message attributes or content.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-04 UTC."],[],[],null,["You can use [Settings](/workspace/gmail/api/v1/reference/users/settings) to\nconfigure forwarding for an account. To be used as a forwarding email address,\nan address must fulfill one of the following criteria:\n\n- The email address has been verified. For further information, see [Creating and verifying forwarding addresses](#create)\n- The email address belongs to the same domain as the sender.\n- The email address belongs to a subdomain within the same domain of the sender.\n- The email address belongs to a domain alias configured as part of the same Google Workspace account.\n\nIf the forwarding email address doesn't adhere to one of these rules, setting up\nforwarding using the API fails.\n\nFor information on how to\n[create](/workspace/gmail/api/v1/reference/users/settings/forwardingAddresses/create),\n[list](/workspace/gmail/api/v1/reference/users/settings/forwardingAddresses/list),\n[get](/workspace/gmail/api/v1/reference/users/settings/forwardingAddresses/get),\nor [delete](/workspace/gmail/api/v1/reference/users/settings/forwardingAddresses/delete)\nforwarding addresses,\nsee the [ForwardingAddresses reference](/workspace/gmail/api/v1/reference/users/settings/forwardingAddresses).\n\nFor information on how to [get](/workspace/gmail/api/v1/reference/users/settings/getAutoForwarding) or\n[update](/workspace/gmail/api/v1/reference/users/settings/updateAutoForwarding) forwarding\nsettings, see the [Settings reference](/workspace/gmail/api/v1/reference/users/settings)\n\nCreating and verifying forwarding addresses\n\nYou must [create](/workspace/gmail/api/v1/reference/users/settings/forwardingAddresses/create)\nforwarding addresses prior to use. In some cases, users must also verify ownership of the\naddress as well.\n\nIf Gmail requires user verification for a forwarding address, the address is returned with the\nstatus `pending`. A verification message is automatically sent to the\ntarget email address. The owner of the email address must complete the verification\nprocess before it can be used.\n\nForwarding addresses that do not require verification have a verification status of `accepted`.\n\nEnabling auto-forwarding\n\nCall the [updateAutoForwarding](/workspace/gmail/api/v1/reference/users/settings/updateAutoForwarding)\nmethod to enable auto-forwarding for an account. The call requires both a registered\nand verified forwarding address as well as an action to take on forwarded messages.\n\nFor example, to enable auto-forwarding and move forwarded messages to the trash: \n\nJava \ngmail/snippets/src/main/java/EnableForwarding.java \n[View on GitHub](https://github.com/googleworkspace/java-samples/blob/main/gmail/snippets/src/main/java/EnableForwarding.java) \n\n```java\nimport com.google.api.client.googleapis.json.GoogleJsonError;\nimport com.google.api.client.googleapis.json.GoogleJsonResponseException;\nimport com.google.api.client.http.HttpRequestInitializer;\nimport com.google.api.client.http.javanet.NetHttpTransport;\nimport com.google.api.client.json.gson.GsonFactory;\nimport com.google.api.services.gmail.Gmail;\nimport com.google.api.services.gmail.GmailScopes;\nimport com.google.api.services.gmail.model.AutoForwarding;\nimport com.google.api.services.gmail.model.ForwardingAddress;\nimport com.google.auth.http.HttpCredentialsAdapter;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport java.io.IOException;\n\n/* Class to demonstrate the use of Gmail Enable Forwarding API */\npublic class EnableForwarding {\n /**\n * Enable the auto-forwarding for an account.\n *\n * @param forwardingEmail - Email address of the recipient whose email will be forwarded.\n * @return forwarding id and metadata, {@code null} otherwise.\n * @throws IOException - if service account credentials file not found.\n */\n public static AutoForwarding enableAutoForwarding(String forwardingEmail) throws IOException {\n /* Load pre-authorized user credentials from the environment.\n TODO(developer) - See https://developers.google.com/identity for\n guides on implementing OAuth2 for your application. */\n GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()\n .createScoped(GmailScopes.GMAIL_SETTINGS_SHARING);\n HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);\n\n // Create the gmail API client\n Gmail service = new Gmail.Builder(new NetHttpTransport(),\n GsonFactory.getDefaultInstance(),\n requestInitializer)\n .setApplicationName(\"Gmail samples\")\n .build();\n\n try {\n // Enable auto-forwarding and move forwarded messages to the trash\n ForwardingAddress address = new ForwardingAddress()\n .setForwardingEmail(forwardingEmail);\n ForwardingAddress createAddressResult = service.users().settings().forwardingAddresses()\n .create(\"me\", address).execute();\n if (createAddressResult.getVerificationStatus().equals(\"accepted\")) {\n AutoForwarding autoForwarding = new AutoForwarding()\n .setEnabled(true)\n .setEmailAddress(address.getForwardingEmail())\n .setDisposition(\"trash\");\n autoForwarding =\n service.users().settings().updateAutoForwarding(\"me\", autoForwarding).execute();\n System.out.println(autoForwarding.toPrettyString());\n return autoForwarding;\n }\n } catch (GoogleJsonResponseException e) {\n // TODO(developer) - handle error appropriately\n GoogleJsonError error = e.getDetails();\n if (error.getCode() == 403) {\n System.err.println(\"Unable to enable forwarding: \" + e.getDetails());\n } else {\n throw e;\n }\n }\n return null;\n }\n}\n```\n\nPython \ngmail/snippet/settings snippets/enable_forwarding.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/settings snippets/enable_forwarding.py) \n\n```python\nimport google.auth\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n\ndef enable_forwarding():\n \"\"\"Enable email forwarding.\n Returns:Draft object, including forwarding id and result meta data.\n\n Load pre-authorized user credentials from the environment.\n TODO(developer) - See https://developers.google.com/identity\n for guides on implementing OAuth2 for the application.\n \"\"\"\n creds, _ = google.auth.default()\n\n try:\n # create gmail api client\n service = build(\"gmail\", \"v1\", credentials=creds)\n\n address = {\"forwardingEmail\": \"gduser1@workspacesamples.dev\"}\n\n # pylint: disable=E1101\n result = (\n service.users()\n .settings()\n .forwardingAddresses()\n .create(userId=\"me\", body=address)\n .execute()\n )\n if result.get(\"verificationStatus\") == \"accepted\":\n body = {\n \"emailAddress\": result.get(\"forwardingEmail\"),\n \"enabled\": True,\n \"disposition\": \"trash\",\n }\n # pylint: disable=E1101\n result = (\n service.users()\n .settings()\n .updateAutoForwarding(userId=\"me\", body=body)\n .execute()\n )\n print(f\"Forwarding is enabled : {result}\")\n\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n result = None\n\n return result\n\n\nif __name__ == \"__main__\":\n enable_forwarding()\n```\n\nTo disable autoforwarding, call [updateAutoForwarding](/workspace/gmail/api/v1/reference/users/settings/updateAutoForwarding)\nand set the `enabled` property to `false`.\n\nForwarding specific messages\n\nAuto-forwarding sends all received messages to the target account. To\nselectively forward messages, use [filters](/workspace/gmail/api/guides/filter_settings)\nto create rules that forward in response to message attributes or content."]]