Gmail API Access using Android

Gmail API Access using Android

This article will guide you through the process of accessing Gmail API from an Android application. This will allow your app to interact with user’s Gmail accounts, such as reading emails, sending emails, and managing labels.

Prerequisites

  • Android Studio
  • A Google Cloud Project
  • Basic understanding of Android development and REST APIs

Steps

1. Creating a Google Cloud Project

  1. Go to the Google Cloud Console: https://console.cloud.google.com/
  2. Create a new project or select an existing one.
  3. Enable the Gmail API for your project.

2. Setting up the Android App

  1. Create a new Android Studio project or open an existing one.
  2. Add the Google Services dependency to your project’s `build.gradle` file (Module: app):
    dependencies {
        implementation 'com.google.android.gms:play-services-auth:20.2.0' 
    }
    
  3. Enable Google Sign-In in your app:
    • Open `AndroidManifest.xml` and add the following permissions:
    • 
      
      
    • Add the following activity to your manifest:
    • 
          
              
              
              
              
          
      
      
    • Replace `your-redirect-uri-scheme` with your custom URI scheme.

3. Obtaining OAuth 2.0 Credentials

  1. Go to the Google Cloud Console and select your project.
  2. Navigate to APIs & Services > Credentials and create OAuth 2.0 client IDs.
  3. Choose “Android” as the application type and provide your package name and SHA-1 certificate fingerprint.
  4. Add the Gmail API scope to your client ID: `https://www.googleapis.com/auth/gmail.readonly` (for read-only access) or `https://www.googleapis.com/auth/gmail.send` (for sending emails) or `https://www.googleapis.com/auth/gmail.modify` (for full access)
  5. Download the JSON file containing your client ID credentials and save it in your project.

4. Implementing Google Sign-In

  1. Set up Google Sign-In in your app following the Google Sign-In documentation.
  2. Use the GoogleSignInAccount object obtained after successful sign-in to retrieve the user’s Google account ID.

5. Making API Requests

  1. Import the necessary libraries:
    import com.google.api.client.extensions.android.http.AndroidHttp;
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.gmail.Gmail;
    import com.google.api.services.gmail.model.Label;
    import com.google.api.services.gmail.model.ListLabelsResponse;
    import com.google.api.services.gmail.model.Message;
    
  2. Create a Gmail service object:
    Gmail service = new Gmail.Builder(
            new NetHttpTransport(), 
            JacksonFactory.getDefaultInstance(), 
            new HttpCredentialsAdapter(GoogleAuthUtil.getToken(
                    YourSignInActivity.this,
                    GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE,
                    scopes,
                    new GoogleAuthUtil.TokenCallback() {
                        @Override
                        public void onTokenAcquired(String token) {
                            // Use the token to authenticate
                        }
    
                        @Override
                        public void onError(String error) {
                            // Handle errors
                        }
                    }
            ))
    ).setApplicationName("Your-App-Name").build();
    
  3. Make API calls using the service object:
    // Example: Get all labels
    ListLabelsResponse labelsResponse = service.users().labels().list("me").execute();
    List
  4. Handle errors and responses:
    try {
        // Your API calls
    } catch (GoogleJsonResponseException e) {
        // Handle errors
    }
    

Example: Reading Emails

// Get the user's inbox
ListMessagesResponse messagesResponse = service.users().messages().list("me").setQ("in:inbox").execute();
List messages = messagesResponse.getMessages();

// Iterate through messages and display content
for (Message message : messages) {
    Message messageDetails = service.users().messages().get("me", message.getId()).execute();

    // Extract relevant information (e.g., sender, subject, body)
    String sender = messageDetails.getPayload().getHeaders().stream()
            .filter(header -> header.getName().equals("From"))
            .findFirst().orElse(null).getValue();

    String subject = messageDetails.getPayload().getHeaders().stream()
            .filter(header -> header.getName().equals("Subject"))
            .findFirst().orElse(null).getValue();

    String body = messageDetails.getPayload().getBody().getData();
    // Decode the Base64-encoded body
    body = new String(Base64.decode(body, Base64.DEFAULT), StandardCharsets.UTF_8);

    // Display the email information
    Log.d("Email", "Sender: " + sender);
    Log.d("Email", "Subject: " + subject);
    Log.d("Email", "Body: " + body);
}

Code Explanation

The provided code snippet demonstrates how to access user’s Gmail messages and extract essential information. It retrieves the user’s inbox messages using the “in:inbox” query parameter, then iterates through the received messages to extract sender, subject, and body information. The body content is Base64-encoded and needs to be decoded before displaying it. You can adapt this example to include other API calls to read, send, or manage emails.

Example: Sending Emails

// Create a new email message
Message message = new Message();
message.setRaw("Your encoded email content");

// Send the message
Message sentMessage = service.users().messages().send("me", message).execute();

Important Notes

  • Ensure your app requests the necessary Gmail API scope when obtaining OAuth 2.0 credentials to perform the desired actions.
  • Handle errors appropriately and provide informative feedback to the user.
  • For detailed API documentation and examples, refer to the official Gmail API documentation: https://developers.google.com/gmail/api/v1


Leave a Reply

Your email address will not be published. Required fields are marked *