pkg398gmail.GmailMethods.java Source code

Java tutorial

Introduction

Here is the source code for pkg398gmail.GmailMethods.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pkg398gmail;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
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.Base64;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Draft;
import com.google.api.services.gmail.model.ListMessagesResponse;
import com.google.api.services.gmail.model.Message;
import com.google.api.services.gmail.model.ListThreadsResponse;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Wellesley
 */
public class GmailMethods {

    // Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
    private static final String SCOPE = "https://www.googleapis.com/auth/gmail.modify";
    private static final String APP_NAME = "Gmail API Quickstart";
    // Email address of the user, or "me" can be used to represent the currently authorized user.
    private static final String USER = "me";
    // Path to the client_secret.json file downloaded from the Developer Console
    private static final String CLIENT_SECRET_PATH = "client_secret.json";

    private static GoogleClientSecrets clientSecrets;
    private static HttpTransport httpTransport = new NetHttpTransport();
    private static JsonFactory jsonFactory = new JacksonFactory();
    private static GoogleAuthorizationCodeFlow flow;
    private static String url;
    private static String code;
    private static GoogleTokenResponse response;
    private static GoogleCredential credential;
    private static Gmail service;
    private static String refreshCode = "1/UGFqD3rQdkT2lSOHbCpSS7-2eCWoWP8zPOyMgHHYyh4";

    public static void main(String args[]) throws IOException {
        normalRun();
    }

    public static void firstRun() throws IOException {
        clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));

        /*
         This approach requires passing a one-time authorization code from your client to your server; 
         this code is used to acquire an access token and refresh tokens for your server.
            
         */
        /*
            
         When a user loads your application for the first time, 
         they are presented with a dialog to grant permission for your application to access their Gmail 
         account with the requested permission scopes. After this initial authorization, 
         the user is ********only presented with the permission dialog************* if your app's
         client ID changes or the requested scopes have changed.
            
         */
        // Allow user to authorize via url.

        flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets,
                Arrays.asList(SCOPE)).setAccessType("offline").setApprovalPrompt("force").build();

        url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();
        System.out.println(
                "Please open the following URL in your browser then type" + " the authorization code:\n" + url);

        // Read code entered by user.
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        code = br.readLine();
        //code="1/UGFqD3rQdkT2lSOHbCpSS7-2eCWoWP8zPOyMgHHYyh4";

        // Generate Credential using retrieved code.
        response = flow.newTokenRequest(code).setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();

        /*
         online use 
         credential = new GoogleCredential()
         .setFromTokenResponse(response);
         */
        // offline use.
        //http://stackoverflow.com/questions/15064636/googlecredential-wont-build-without-googlecredential-builder

        //http://stackoverflow.com/questions/10533203/fetching-access-token-from-refresh-token-using-java

        createCredential();

        // now we get the refresh token. We use this refresh the user session.      
        String refToken = credential.getRefreshToken();
        System.out.println("Refresh Token:  " + refToken);

        // Create a new authorized Gmail API client
        createService();
        // send message
        send();

    }

    public static void normalRun() throws IOException {
        clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));
        createCredentialWithRefresh();

        // now we get the refresh token. We use this refresh the user session.      
        String refToken = credential.getRefreshToken();
        System.out.println("Refresh Token:  " + refToken);

        // Create a new authorized Gmail API client
        createService();
        // send message
        send();
    }

    public static void createCredential() {
        credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                .setClientSecrets(clientSecrets).build().setFromTokenResponse(response);
    }

    public static void createCredentialWithRefresh() {
        credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                .setClientSecrets(clientSecrets).build().setRefreshToken(refreshCode);
    }

    public static void createService() {
        service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME).build();
    }

    public static void send() throws IOException {
        try {
            sendMessage(service, "me", createEmail("wra216@lehigh.edu", "me", "test", "test"));
        } catch (MessagingException ex) {
            Logger.getLogger(GmailApiQuickstart.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // get all the messages with the labels.
    public static List<Message> listMessagesWithLabels(Gmail service, String userId, List<String> labelIds)
            throws IOException {
        ListMessagesResponse response = service.users().messages().list(userId).setLabelIds(labelIds).execute();

        List<Message> messages = new ArrayList<Message>();
        while (response.getMessages() != null) {
            messages.addAll(response.getMessages());
            if (response.getNextPageToken() != null) {
                String pageToken = response.getNextPageToken();
                response = service.users().messages().list(userId).setLabelIds(labelIds).setPageToken(pageToken)
                        .execute();
            } else {
                break;
            }
        }

        for (Message message : messages) {
            System.out.println(message.toPrettyString());
        }

        return messages;
    }

    public static MimeMessage createEmail(String to, String from, String subject, String bodyText)
            throws MessagingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);

        email.setFrom(new InternetAddress(from));
        email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        email.setSubject(subject);
        email.setText(bodyText);
        return email;
    }

    public static Draft createDraft(Gmail service, String userId, MimeMessage email)
            throws MessagingException, IOException {
        Message message = createMessageWithEmail(email);
        Draft draft = new Draft();
        draft.setMessage(message);
        draft = service.users().drafts().create(userId, draft).execute();

        System.out.println("draft id: " + draft.getId());
        System.out.println(draft.toPrettyString());
        return draft;
    }

    // include attachments.
    public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
            String fileDir, String filename) throws MessagingException, IOException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);
        InternetAddress tAddress = new InternetAddress(to);
        InternetAddress fAddress = new InternetAddress(from);

        email.setFrom(fAddress);
        email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
        email.setSubject(subject);

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(bodyText, "text/plain");
        mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        mimeBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileDir + filename);

        mimeBodyPart.setDataHandler(new DataHandler(source));
        mimeBodyPart.setFileName(filename);
        String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
        mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
        mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

        multipart.addBodyPart(mimeBodyPart);

        email.setContent(multipart);

        return email;
    }

    // method to send message.
    public static void sendMessage(Gmail service, String userId, MimeMessage email)
            throws MessagingException, IOException {
        Message message = createMessageWithEmail(email);
        message = service.users().messages().send(userId, message).execute();

        System.out.println("Message id: " + message.getId());
        System.out.println(message.toPrettyString());
    }

    public static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        email.writeTo(bytes);
        String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
    }

}