This document explains how to configure email forwarding in the Gmail API.

You can use the
[`settings`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings) resource to
configure forwarding for an account. To use an email address for forwarding, it
must meet one of the following criteria:

- The email address is verified. For more information, see [Create and verify
  forwarding addresses](https://developers.google.com/workspace/gmail/api/guides/forwarding_settings#create-verify).
- The email address belongs to the same domain as the sender.
- The email address belongs to a subdomain within the same domain as the sender.
- The email address belongs to a domain alias configured as part of the same Google Workspace account.

If the forwarding email address doesn't adhere to one of these rules, setting up
forwarding using the API fails.

For information on how to
[create](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.forwardingAddresses/create),
[list](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.forwardingAddresses/list),
[get](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.forwardingAddresses/get),
or
[delete](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.forwardingAddresses/delete)
forwarding addresses, see the methods on the
[`settings.forwardingAddresses`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.forwardingAddresses)
resource.

For information on how to
[get](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings/getAutoForwarding)
or
[update](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings/updateAutoForwarding)
the auto-forwarding settings, see the methods on the
[`settings`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings) resource.

## Create and verify forwarding addresses

You must
[create](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.forwardingAddresses/create)
forwarding addresses before you use them. In some cases, users must also verify
ownership of the address.

If Gmail requires user verification for a forwarding address, the API
returns the address with a
[`VerificationStatus`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.forwardingAddresses#verificationstatus)
of `pending`. Gmail automatically sends a verification message to
the target email address. The owner of the email address must complete the
verification process before you can use it.

Forwarding addresses that don't require verification have a verification status
of `accepted`.

## Enable automatic forwarding

You can choose to forward all of your new messages to another email address.

To do so, call the
[`updateAutoForwarding`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings/updateAutoForwarding)
method to enable auto-forwarding for an account. The call requires a registered
and verified forwarding address and an action to take on forwarded messages.
Set these values in the
[`AutoForwarding`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/AutoForwarding)
object.

Use the
[`disposition`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/AutoForwarding#FIELDS.disposition)
field to set the message state after the message is forwarded. Although the
default value is `dispositionUnspecified`, you can't set this field to
`dispositionUnspecified`.

The following code samples show how to enable auto-forwarding and then move
forwarded messages to the trash:

### Java

gmail/snippets/src/main/java/EnableForwarding.java [View on GitHub](https://github.com/googleworkspace/java-samples/blob/main/gmail/snippets/src/main/java/EnableForwarding.java)

```java
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.AutoForwarding;
import com.google.api.services.gmail.model.ForwardingAddress;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;

/* Class to demonstrate the use of Gmail Enable Forwarding API */
public class EnableForwarding {
  /**
   * 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.
   */
  public static AutoForwarding enableAutoForwarding(String forwardingEmail) throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(GmailScopes.GMAIL_SETTINGS_SHARING);
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

    // Create the gmail API client
    Gmail service = new Gmail.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Gmail samples")
        .build();

    try {
      // Enable auto-forwarding and move forwarded messages to the trash
      ForwardingAddress address = new ForwardingAddress()
          .setForwardingEmail(forwardingEmail);
      ForwardingAddress createAddressResult = service.users().settings().forwardingAddresses()
          .create("me", address).execute();
      if (createAddressResult.getVerificationStatus().equals("accepted")) {
        AutoForwarding autoForwarding = new AutoForwarding()
            .setEnabled(true)
            .setEmailAddress(address.getForwardingEmail())
            .setDisposition("trash");
        autoForwarding =
            service.users().settings().updateAutoForwarding("me", autoForwarding).execute();
        System.out.println(autoForwarding.toPrettyString());
        return autoForwarding;
      }
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 403) {
        System.err.println("Unable to enable forwarding: " + e.getDetails());
      } else {
        throw e;
      }
    }
    return null;
  }
}
```

### Python

gmail/snippet/settings snippets/enable_forwarding.py [View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/settings snippets/enable_forwarding.py)

```python
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def enable_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 client
    service = build("gmail", "v1", credentials=creds)

    address = {"forwardingEmail": "gduser1@workspacesamples.dev"}

    # pylint: disable=E1101
    result = (
        service.users()
        .settings()
        .forwardingAddresses()
        .create(userId="me", body=address)
        .execute()
    )
    if result.get("verificationStatus") == "accepted":
      body = {
          "emailAddress": result.get("forwardingEmail"),
          "enabled": True,
          "disposition": "trash",
      }
      # pylint: disable=E1101
      result = (
          service.users()
          .settings()
          .updateAutoForwarding(userId="me", body=body)
          .execute()
      )
      print(f"Forwarding is enabled : {result}")

  except HttpError as error:
    print(f"An error occurred: {error}")
    result = None

  return result


if __name__ == "__main__":
  enable_forwarding()
```

To disable auto-forwarding, call the
[`updateAutoForwarding`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings/updateAutoForwarding)
method and set the
[`enabled`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/AutoForwarding#FIELDS.enabled)
field on the `AutoForwarding` object to `false`.

## Forward specific messages

Automatic forwarding sends all received Gmail messages to the
target account. To forward specific messages, set up a
[filter](https://developers.google.com/workspace/gmail/api/guides/filter_settings) to create rules that
forward messages in response to message attributes or content.

To forward messages to multiple accounts, create a filter for every forwarding
email address.