### Install Python Client Library Manually
Source: https://developers.google.com/workspace/gmail/api/downloads
Manually install the Python client library by downloading, unpacking, and running the setup script.
```bash
python setup.py install
```
--------------------------------
### Postmaster Tools API Quickstart Example
Source: https://developers.google.com/workspace/gmail/postmaster/quickstart/python
This Python script demonstrates how to authenticate with the Postmaster Tools API, list domains, and query domain statistics. Ensure you have `credentials.json` and `token.pickle` set up.
```python
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient import errors
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/postmaster.traffic.readonly']
def main():
"""Shows basic usage of the PostmasterTools v2 API.
Prints the visible domains on user's domain dashboard in https://postmaster.google.com/managedomains.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmailpostmastertools', 'v2', credentials=creds)
response = service.domains().list().execute()
domains = response.get('domains')
if not domains:
print('No domains found.')
else:
print('Domains:')
for domain in domains:
print(domain)
print('Querying stats for %s' % domain['name'])
try:
stats = service.domains().domainStats().query(
parent=domain['name'],
startDate={'year': 2024, 'month': 1, 'day': 1},
endDate={'year': 2024, 'month': 1, 'day': 7}).execute()
print(stats)
except errors.HttpError as err:
print('An error occurred during stats query: %s' % err)
if __name__ == '__main__':
main()
```
--------------------------------
### HTML Setup for Gmail API Quickstart
Source: https://developers.google.com/workspace/gmail/api/quickstart/js
Paste this HTML code into your index.html file to set up the basic structure for the Gmail API quickstart.
```html
Gmail API Quickstart
Gmail API Quickstart
Check the console for log output.
```
--------------------------------
### Run the Python Quickstart Sample
Source: https://developers.google.com/workspace/gmail/api/quickstart/python
Execute this command in your working directory to build and run the quickstart application. The first time it runs, it will prompt for authorization.
```bash
python3 quickstart.py
```
--------------------------------
### Run the Java Quickstart
Source: https://developers.google.com/workspace/gmail/postmaster/quickstart/java
Execute this command in your terminal to run the Java quickstart application. The first time it runs, it will prompt for authorization.
```bash
gradle run
```
--------------------------------
### Install Google Client Library for Python
Source: https://developers.google.com/workspace/gmail/api/quickstart/python
Install the necessary Google client libraries for Python to interact with Google APIs. This command upgrades existing installations.
```bash
python3 -m pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
```
--------------------------------
### Install http-server Package
Source: https://developers.google.com/workspace/gmail/api/quickstart/js
Install the http-server package to serve your web application locally. This is a prerequisite for running the sample.
```bash
npm install http-server
```
--------------------------------
### Install Python Client Library using Setuptools
Source: https://developers.google.com/workspace/gmail/api/downloads
Use Setuptools to install or upgrade the Google API client library for Python. You might need to run `sudo` first.
```bash
easy_install --upgrade google-api-python-client
```
--------------------------------
### Install Node.js Client Libraries
Source: https://developers.google.com/workspace/gmail/api/quickstart/nodejs
Install the necessary Google API client and local authentication libraries using npm. This is the first step before setting up the application.
```bash
npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save
```
--------------------------------
### Install Python Client Library using pip
Source: https://developers.google.com/workspace/gmail/api/downloads
Use pip to install or upgrade the Google API client library for Python. You might need to run `sudo` first. This is the preferred method for managed installation.
```bash
pip install --upgrade google-api-python-client
```
--------------------------------
### Start Antigravity CLI
Source: https://developers.google.com/workspace/gmail/api/guides/configure-mcp-server
Use this command to start the Antigravity Command Line Interface.
```bash
agy
```
--------------------------------
### Full Resource Response Example
Source: https://developers.google.com/workspace/gmail/api/guides/performance
The full resource data includes numerous fields. This example shows a subset for illustration.
```json
{
"kind": "demo",
...
"items": [
{
"title": "First title",
"comment": "First comment.",
"characteristics": {
"length": "short",
"accuracy": "high",
"followers": ["Jo", "Will"],
},
"status": "active",
...
},
{
"title": "Second title",
"comment": "Second comment.",
"characteristics": {
"length": "long",
"accuracy": "medium"
"followers": [ ],
},
"status": "pending",
...
},
...
]
}
```
--------------------------------
### Install Google API Client Gem for Ruby
Source: https://developers.google.com/workspace/gmail/api/downloads
Install the `google-api-client` gem using RubyGems. You might need to prepend commands with `sudo`.
```bash
gem install google-api-client
```
--------------------------------
### Install NuGet Package for .NET
Source: https://developers.google.com/workspace/gmail/api/downloads
Install the Google.Apis. NuGet package to use the Gmail API client library for .NET.
```csharp
Install the NuGet package: Google.Apis.
```
--------------------------------
### Start Local Web Server
Source: https://developers.google.com/workspace/gmail/api/quickstart/js
Start a local web server using npx http-server on port 8000. This command is used to serve your JavaScript application during development.
```bash
npx http-server -p 8000
```
--------------------------------
### Train Reservation Example (JSON-LD)
Source: https://developers.google.com/workspace/gmail/markup/reference/train-reservation
This snippet shows a complete example of the TrainReservation schema using JSON-LD, including all possible fields.
```json
```
--------------------------------
### Subscription Handler for POST and GET Requests
Source: https://developers.google.com/workspace/gmail/markup/actions/end-to-end-example
This script handles subscription requests via POST and lists existing subscriptions via GET. POST requests insert a new subscription into the Datastore, while GET requests retrieve and display up to 1000 subscriptions.
```python
import webapp2
from emailsender import EmailSender
from google.appengine.ext import db
class SubscribeHandler(webapp2.RequestHandler):
def post(self):
user_id = self.request.get('user')
# insert the subscription into the Datastore
subscription = Subscription(user_id=user_id)
subscription.put()
def get(self):
# retrieve up to 1000 subscriptions from the Datastore
subscriptions = Subscription.all().fetch(1000)
if not subscriptions:
self.response.write('No subscriptions')
return
count = len(subscriptions)
for s in subscriptions:
self.response.write('%s subscribed ' % (s.user_id))
self.response.write(' ')
self.response.write('%d subscriptions.' % (count))
class Subscription(db.Model):
user_id = db.TextProperty(required=True)
```
--------------------------------
### Example: Authenticate Personal Notes with amp-list
Source: https://developers.google.com/workspace/gmail/ampemail/authenticating-requests
This example shows how to use a specific access token in the URL for fetching personalized data via ``. The endpoint is responsible for validating the token.
```html
{{note}}
```
--------------------------------
### Simple Upload Request Example
Source: https://developers.google.com/workspace/gmail/api/guides/uploads
This example demonstrates a simple upload request for the Gmail API, including necessary headers like `Content-Type`, `Content-Length`, and `Authorization`. The `uploadType=media` parameter is crucial.
```http
POST /upload/gmail/v1/users/userId/messages/send?uploadType=media HTTP/1.1
Host: www.googleapis.com
Content-Type: message/rfc822
Content-Length: number_of_bytes_in_file
Authorization: Bearer your_auth_token
Email Message data
```
--------------------------------
### Run the Node.js Sample
Source: https://developers.google.com/workspace/gmail/api/quickstart/nodejs
Execute the Node.js quickstart application from your terminal. The first run will prompt for authorization.
```bash
node .
```
--------------------------------
### Build and Run Go Sample
Source: https://developers.google.com/workspace/gmail/api/quickstart/go
Execute this command in your working directory to build and run the Go sample application. The first time it runs, it will prompt for authorization.
```bash
go run quickstart.go
```
--------------------------------
### Full Microdata Example with Mobile Deep Links
Source: https://developers.google.com/workspace/gmail/markup/actions/declaring-actions
This Microdata example shows an EmailMessage schema with a ViewAction, including 'target' meta tags for web, Android, and iOS deep links. The fallback web URL is used if the app is not installed.
```html
... information about the movie ...
```
--------------------------------
### Get Thread
Source: https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.threads
Gets the specified thread.
```APIDOC
## GET users.threads.get
### Description
Gets the specified thread.
### Method
GET
### Endpoint
`GET https://www.googleapis.com/gmail/v1/users/{userId}/threads/{id}`
```
--------------------------------
### Gmail API Quickstart in Go
Source: https://developers.google.com/workspace/gmail/api/quickstart/go
This Go program authenticates with the Gmail API using OAuth2, retrieves user credentials, and lists the user's labels. Ensure you have a `credentials.json` file in the same directory.
```go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/option"
)
// Retrieve a token, saves the token, then returns the generated client.
func getClient(config *oauth2.Config) *http.Client {
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
tokFile := "token.json"
tok, err := tokenFromFile(tokFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokFile, tok)
}
return config.Client(context.Background(), tok)
}
// Request a token from the web, then returns the retrieved token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the " +
"authorization code: \n%v\n", authURL)
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
log.Fatalf("Unable to read authorization code: %v", err)
}
tok, err := config.Exchange(context.TODO(), authCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return tok
}
// Retrieves a token from a local file.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
tok := &oauth2.Token{}
err = json.NewDecoder(f).Decode(tok)
return tok, err
}
// Saves a token to a file path.
func saveToken(path string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", path)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}
func main() {
ctx := context.Background()
b, err := os.ReadFile("credentials.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
// If modifying these scopes, delete your previously saved token.json.
config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(config)
srv, err := gmail.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Unable to retrieve Gmail client: %v", err)
}
user := "me"
r, err := srv.Users.Labels.List(user).Do()
if err != nil {
log.Fatalf("Unable to retrieve labels: %v", err)
}
if len(r.Labels) == 0 {
fmt.Println("No labels found.")
return
}
fmt.Println("Labels:")
for _, l := range r.Labels {
fmt.Printf("- %s\n", l.Name)
}
}
```
--------------------------------
### Get Send-As Alias
Source: https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.sendAs
Gets the specified send-as alias.
```APIDOC
## GET /v1/users.settings/sendAs/{aliasId}
### Description
Gets the specified send-as alias.
### Method
GET
### Endpoint
/v1/users.settings/sendAs/{aliasId}
### Parameters
#### Path Parameters
- **aliasId** (string) - Required - The ID of the send-as alias to retrieve.
### Response
#### Success Response (200)
- **alias** (object) - The requested send-as alias.
- **sendEmailAddress** (string) - The email address of the alias.
- **displayName** (string) - The display name of the alias.
- **replyToAddresses** (array) - A list of reply-to addresses.
- (string) - A reply-to email address.
- **isDefault** (boolean) - Whether this is the default send-as alias.
- **verificationStatus** (string) - The verification status of the alias.
- **securityMode** (string) - The security mode for sending via SMTP.
- **smtpSettings** (object) - SMTP settings for sending mail through this alias.
- **hostName** (string) - The SMTP host name.
- **port** (integer) - The SMTP port.
- **userName** (string) - The user name for SMTP authentication.
- **useAuth** (boolean) - Whether to use SMTP authentication.
- **sslEnabled** (boolean) - Whether to use SSL for SMTP.
- **tlsEnabled** (boolean) - Whether to use TLS for SMTP.
```
--------------------------------
### get
Source: https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.sendAs.smimeInfo
Gets the specified S/MIME config for the specified send-as alias.
```APIDOC
## GET /gmail/v1/users/{userId}/settings/sendAs/{sendAs}/smimeInfo/{id}
### Description
Gets the specified S/MIME config for the specified send-as alias.
### Method
GET
### Endpoint
`/gmail/v1/users/{userId}/settings/sendAs/{sendAs}/smimeInfo/{id}`
### Parameters
#### Path Parameters
- **userId** (string) - Required - The user's email address. The special value `me` can be used to indicate the authenticated user.
- **sendAs** (string) - Required - The send-as address to retrieve the S/MIME config from.
- **id** (string) - Required - The ID of the S/MIME config to retrieve.
```
--------------------------------
### REST Resource: v1.domains - get
Source: https://developers.google.com/workspace/gmail/postmaster/reference/rest
Gets a specific domain registered by the client.
```APIDOC
## GET /v1/{name=domains/*}
### Description
Gets a specific domain registered by the client.
### Method
GET
### Endpoint
/v1/{name=domains/*}
```
--------------------------------
### REST Resource: v1.domains.trafficStats - get
Source: https://developers.google.com/workspace/gmail/postmaster/reference/rest
Get traffic statistics for a domain on a specific date.
```APIDOC
## GET /v1/{name=domains/*/trafficStats/*}
### Description
Get traffic statistics for a domain on a specific date.
### Method
GET
### Endpoint
/v1/{name=domains/*/trafficStats/*}
```
--------------------------------
### Gmail API Quickstart Script
Source: https://developers.google.com/workspace/gmail/api/quickstart/python
This Python script demonstrates basic usage of the Gmail API by listing user labels. It handles authentication using OAuth 2.0 and saves credentials for future use.
```python
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
"credentials.json", SCOPES
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.json", "w") as token:
token.write(creds.to_json())
try:
# Call the Gmail API
service = build("gmail", "v1", credentials=creds)
results = service.users().labels().list(userId="me").execute()
labels = results.get("labels", [])
if not labels:
print("No labels found.")
return
print("Labels:")
for label in labels:
print(label["name"])
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f"An error occurred: {error}")
if __name__ == "__main__":
main()
```
--------------------------------
### Create Project Structure
Source: https://developers.google.com/workspace/gmail/api/quickstart/java
Initializes a new basic Gradle project and creates necessary directories for Java source and resources.
```bash
gradle init --type basic
mkdir -p src/main/java src/main/resources
```
--------------------------------
### Get Verification Token
Source: https://developers.google.com/workspace/gmail/postmaster/reference/rest/v2/domains
Gets a verification token used for verifying a user's ownership over a domain.
```APIDOC
## GET /gmail/v2/users/{userId}/domains/{domainId}/verificationToken
### Description
Gets a verification token used for verifying a user's ownership over a domain.
### Method
GET
### Endpoint
/gmail/v2/users/{userId}/domains/{domainId}/verificationToken
```
--------------------------------
### Run the Java Sample
Source: https://developers.google.com/workspace/gmail/api/quickstart/java
Execute this command in your terminal to run the Java sample application. The first execution will trigger an authorization flow.
```bash
gradle run
```
--------------------------------
### Example SASL XOAUTH2 Error Response (Base64 Encoded)
Source: https://developers.google.com/workspace/gmail/imap/xoauth2-protocol
A base64 encoded example of a server error challenge.
```text
eyJzdGF0dXMiOiI0MDEiLCJzY2hlbWVzIjoiYmVhcmVyIG1hYyIsInNjb3BlIjoiaHR0cHM6Ly9t
YWlsLmdvb2dsZS5jb20vIn0K
```
--------------------------------
### Node.js Gmail API Quickstart Application
Source: https://developers.google.com/workspace/gmail/api/quickstart/nodejs
This Node.js code snippet sets up authentication and lists the labels in a user's Gmail account using the Gmail API. Ensure you have a 'credentials.json' file in your working directory.
```javascript
import path from 'node:path';
import process from 'node:process';
import {authenticate} from '@google-cloud/local-auth';
import {google} from 'googleapis';
// The scope for reading Gmail labels.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
// The path to the credentials file.
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
/**
* Lists the labels in the user's account.
*/
async function listLabels() {
// Authenticate with Google and get an authorized client.
const auth = await authenticate({
scopes: SCOPES,
keyfilePath: CREDENTIALS_PATH,
});
// Create a new Gmail API client.
const gmail = google.gmail({version: 'v1', auth});
// Get the list of labels.
const result = await gmail.users.labels.list({
userId: 'me',
});
const labels = result.data.labels;
if (!labels || labels.length === 0) {
console.log('No labels found.');
return;
}
console.log('Labels:');
// Print the name of each label.
labels.forEach((label) => {
console.log(`- ${label.name}`);
});
}
await listLabels();
```
--------------------------------
### Create a working directory
Source: https://developers.google.com/workspace/gmail/api/quickstart/go
Creates a new directory for your project. This is the first step in setting up your workspace.
```bash
mkdir quickstart
```
--------------------------------
### Postmaster Tools API Quickstart
Source: https://developers.google.com/workspace/gmail/postmaster/quickstart/java
This Java code snippet demonstrates how to authenticate with the Postmaster Tools API and retrieve a list of domains. It also shows how to query domain statistics for a specified date range. Ensure you have a `credentials.json` file in your resources and have configured your `build.gradle` file.
```java
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmailpostmastertools.v2.PostmasterTools;
import com.google.api.services.gmailpostmastertools.v2.model.*;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class PostmasterToolsApiQuickStart {
private static final String APPLICATION_NAME = "PostmasterTools API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List SCOPES = Collections.singletonList("https://www.googleapis.com/auth/postmaster.readonly");
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
* @param HTTP_TRANSPORT The network HTTP Transport.
* @return An authorized Credential object.
* @throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = PostmasterToolsApiQuickStart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8891).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
PostmasterTools postmasterTools = new PostmasterTools.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
List domains = postmasterTools.domains().list().execute().getDomains();
if (domains == null || domains.isEmpty()) {
System.out.println("No domains found!");
} else {
for (Domain domain : domains) {
System.out.println(domain.toPrettyString());
System.out.println("Querying stats for " + domain.getName());
try {
Date startDate = new Date().setYear(2024).setMonth(1).setDay(1);
Date endDate = new Date().setYear(2024).setMonth(1).setDay(7);
QueryDomainStatsResponse statsResponse = postmasterTools.domains().domainStats()
.query(domain.getName())
.setStartDate(startDate)
.setEndDate(endDate)
.execute();
System.out.println(statsResponse.toPrettyString());
} catch (Exception e) {
System.out.println("Error querying stats: " + e.getMessage());
}
}
}
}
}
```
--------------------------------
### Gmail API Java Quickstart
Source: https://developers.google.com/workspace/gmail/api/quickstart/java
This snippet demonstrates how to authenticate with the Gmail API using OAuth 2.0 and list all labels in the user's Gmail account. Ensure you have a 'credentials.json' file in your resources and the 'tokens' directory is writable.
```java
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
/* class to demonstrate use of Gmail list labels API */
public class GmailQuickstart {
/**
* Application name.
*/
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
/**
* Global instance of the JSON factory.
*/
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
/**
* Directory to store authorization tokens for this application.
*/
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List SCOPES = Collections.singletonList(GmailScopes.GMAIL_LABELS);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
*
* @param HTTP_TRANSPORT The network HTTP Transport.
* @return An authorized Credential object.
* @throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
throws IOException {
// Load client secrets.
InputStream in = GmailQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
//returns an authorized Credential object.
return credential;
}
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// Print the labels in the user's account.
String user = "me";
ListLabelsResponse listResponse = service.users().labels().list(user).execute();
List