Mail Server Solution(4)gmail API Demo

Mail Server Solution(4)gmail API Demo

1. API Introduction
It should be working. Here is some API I may need later.
gmail.users.messages.list
     userId-email address
     labelIds-INBOX
     q-job.craigslist.org
gmail.users.messages.get
    userId-email address
    id-message id I get in the previous API
    response-playload, sizeEstimate
gmail.users.messages.attachments.get
    userId-email address
    messageId-message id I get in the first API
    id-attachment file id I get in the previous API
    fields-data and size

2. Admin Console Configuration
Visit the google developer’s console
https://console.developers.google.com

Go to APIs&Auth —> Credentials —> I select the installed application for demo

After that I download a JSON file which will have some keys there with name similar to xxxx.json
Actually, I should use this one later
https://developers.google.com/identity/protocols/OAuth2?hl=en_US#serviceaccount

3. Set up Sample with gradle and JAVA
Install Gradle Again with Latest Version
That is amazing, the version is gradle 2.5 now. I was using 1.1 or 1.2 before.
http://sillycat.iteye.com/blog/1074642
http://sillycat.iteye.com/blog/2090147

Place it in the right place and add to the path.

mkdir and prepare the working directory
> pwd
/Users/carl/work/gradle/gmailapi
> gradle init --type basic

Generate the source directory
> mkdir -p src/main/java src/main/resources
Copy and prepare the JSON key file under src/main/resources
Copy and Place the JAVA data there. It is working pretty well.

build.gradle
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'eclipse'

mainClassName = 'com.sillycat.gmailapi.GmailQuickstart'
sourceCompatibility = 1.7
targetCompatibility = 1.7
version = '1.0'

repositories {
    jcenter()
    mavenCentral()
}

dependencies {
    compile 'com.google.api-client:google-api-client:1.20.0'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.20.0'
    compile 'com.google.apis:google-api-services-gmail:v1-rev29-1.20.0'
    compile 'org.slf4j:slf4j-api:1.7.12'
    testCompile 'junit:junit:4.12'
}

Here is the codes
package com.sillycat.gmailapi;

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.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;

import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.*;
import com.google.api.services.gmail.Gmail;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class GmailQuickstart {

/** Application name. */
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";

/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"),
".credentials/gmail-api-quickstart");

/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory
.getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/** Global instance of the scopes required by this quickstart. */
private static final List<String> SCOPES = Arrays
.asList(GmailScopes.GMAIL_LABELS);

static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}

/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in = GmailQuickstart.class
.getResourceAsStream("/client_secret.json");
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(DATA_STORE_FACTORY)
.setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow,
new LocalServerReceiver()).authorize("user");
System.out.println("Credentials saved to "
+ DATA_STORE_DIR.getAbsolutePath());
return credential;
}

/**
* Build and return an authorized Gmail client service.
*
* @return an authorized Gmail client service
* @throws IOException
*/
public static Gmail getGmailService() throws IOException {
Credential credential = authorize();
return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}

public static void main(String[] args) throws IOException {
// Build a new authorized API client service.
Gmail service = getGmailService();

// Print the labels in the user's account.
String user = "me";
ListLabelsResponse listResponse = service.users().labels().list(user)
.execute();
List<Label> labels = listResponse.getLabels();
if (labels.size() == 0) {
System.out.println("No labels found.");
} else {
System.out.println("Labels:");
for (Label label : labels) {
System.out.printf("- %s\n", label.getName());
}
}
}

}

Generate the eclipse structure and import to eclipse
> gradle eclipse

Run the application
> gradle run --stacktrace

References:
https://developers.google.com/gmail/api/
https://developers.google.com/gmail/api/quickstart/java
https://developers.google.com/api-client-library/java/apis/gmail/v1
https://developers.google.com/apis-explorer/#p/gmail/v1/


猜你喜欢

转载自sillycat.iteye.com/blog/2232877
今日推荐