Java Mail API Using GMAIL OAuth API In Android


Gmail API

Java mail API is used to send mail from Android applications directly. But Google was restricting  mail access by third parties like Java mail API for Gmail accounts for security reasons. To proceed further, you need to generate OAuth key in Google API Console and to generate OAuth key, you need SHA1 Key.


You need to follow the steps mentioned below.

Step 1 - Generate SHA1 Key.

Step 2 - Turn ON Gmail API

Step 3 - Coding Part.


Step 1 - Generate SHA1 Key

To generate SHA1 Key, Open your terminal or command prompt and paste the following, hit enter to get your SHA1 Key.

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android


Step 2 - Turn On Gmail API

  1. Open Google API Console and create a new project in your Dashboard.


  2. Click Enable APIS and Services and go to API Page. Then select Gmail API and select “Enable API”.


  3. Then select Credentials in the side menu and select “Create Credentials” in Credentials Tab. And Select “OAuth Client ID” as shown in the screen.


  4. Then Select “Android” and Paste your SHA1 Key generated in the previous step & Package Name of your Application.


  5. Then Click “Create”

Step 3 - Coding Part

In this, we will see the coding part of your Application. I have split this part into 4 steps as shown below.

  1. Creating New Project with Android Studio
  2. Setting up AndroidManifest for the project
  3. Setting up Gmail and Java mail API.
  4. Implementation of the functionality.

Without any more introduction, we will jump into the coding part.

Creating New Projects with Android Studio

  1. Open Android Studio and Select Create new project.
  2. Name the project as per your wish and select your activity template.


  3. Click “finish” button to create a new project in Android Studio.

Setting up AndroidManifest for the project

The following permissions are very important and don’t forget to add them to your Manifest file.

  1. <uses-permission android:name="android.permission.INTERNET"/>  
  2. <uses-permission android:name="android.permission.GET_ACCOUNTS"/>  

From Android Version 6.0 (Marshmallow), we need to prompt the user to allow these permissions.

Setting up Gmail and Java mail API

You need the following Libraries to send mail from the application directly.

  1. dependencies {  
  2.     compile fileTree(dir: 'libs', include: ['*.jar'])  
  3.     compile ''  
  4.     compile ''  
  5.     compile('') {  
  6.         exclude group: 'org.apache.httpcomponents'  
  7.     }  
  8.     compile('') {  
  9.         exclude group: 'org.apache.httpcomponents'  
  10.     }  
  11.     compile files('libs/mail.jar')  
  12.     compile files('libs/activation.jar')  
  13.     compile files('libs/additionnal.jar')  
  14. }  

The Jar Libraries can be downloaded from here and these libraries are in your libs folder.

Implementing the functionality

In this step, we will  be implementing the functionality.

  • Initialize the Google API Client as in the following.
    1. // Initialize credentials and service object.  
    2. mCredential = GoogleAccountCredential.usingOAuth2(  
    3.         getApplicationContext(), Arrays.asList(SCOPES))  
    4.         .setBackOff(new ExponentialBackOff());  
  • Here SCOPES is the array used to specify the scope for your application.
    1. private static final String[] SCOPES = {  
    2.         GmailScopes.GMAIL_LABELS,  
    3.         GmailScopes.GMAIL_COMPOSE,  
    4.         GmailScopes.GMAIL_INSERT,  
    5.         GmailScopes.GMAIL_MODIFY,  
    6.         GmailScopes.GMAIL_READONLY,  
    7.         GmailScopes.MAIL_GOOGLE_COM  
    8. };  
  • The following line is used to start Account Pick in Android.
    1. // Start a dialog from which the user can choose an account  
    2. startActivityForResult(mCredential.newChooseAccountIntent(), Utils.REQUEST_ACCOUNT_PICKER);  

Method to send Mail

  1. // Method to send email  
  2. private String sendMessage(Gmail service, String userId, MimeMessage email)  
  3.         throws MessagingException, IOException {  
  4.     Message message = createMessageWithEmail(email);  
  5.     // GMail's official method to send email with oauth2.0  
  6.     message = service.users().messages().send(userId, message).execute();  
  8.     System.out.println("Message id: " + message.getId());  
  9.     System.out.println(message.toPrettyString());  
  10.     return message.getId();  
  11. }  

Method to Create Email with Attachment

  1. private MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException {  
  2.     Properties props = new Properties();  
  3.     Session session = Session.getDefaultInstance(props, null);  
  5.     MimeMessage email = new MimeMessage(session);  
  6.     InternetAddress tAddress = new InternetAddress(to);  
  7.     InternetAddress fAddress = new InternetAddress(from);  
  9.     email.setFrom(fAddress);  
  10.     email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);  
  11.     email.setSubject(subject);  
  13.     // Create Multipart object and add MimeBodyPart objects to this object  
  14.     Multipart multipart = new MimeMultipart();  
  16.     // Changed for adding attachment and text  
  17.     // This line is used for sending only text messages through mail  
  18.     // email.setText(bodyText);  
  20.     BodyPart textBody = new MimeBodyPart();  
  21.     textBody.setText(bodyText);  
  22.     multipart.addBodyPart(textBody);  
  24.     if (!(activity.fileName.equals(""))) {  
  25.         // Create new MimeBodyPart object and set DataHandler object to this object  
  26.         MimeBodyPart attachmentBody = new MimeBodyPart();  
  27.         String filename = activity.fileName; // change accordingly  
  28.         DataSource source = new FileDataSource(filename);  
  29.         attachmentBody.setDataHandler(new DataHandler(source));  
  30.         attachmentBody.setFileName(filename);  
  31.         multipart.addBodyPart(attachmentBody);  
  32.     }  
  34.     // Set the multipart object to the message object  
  35.     email.setContent(multipart);  
  36.     return email;  
  37. }  
  39. private Message createMessageWithEmail(MimeMessage email)  
  40.         throws MessagingException, IOException {  
  41.     ByteArrayOutputStream bytes = new ByteArrayOutputStream();  
  42.     email.writeTo(bytes);  
  43.     String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());  
  44.     Message message = new Message();  
  45.     message.setRaw(encodedEmail);  
  46.     return message;  
  47. }  

We can send mail with and without attachments directly from your Android application. If you want to send a mail attachment, you need to add the following permission in your Manifest file and you need to add permission checking methods for Android 6.0 and higher versions.

  1. <!--Added for Accessing External Storage-->  
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  


  • You should add the following lines in proguard while releasing your APK.

    keep class**
  • You should add separate SHA1 Key for Debug and Release mode for your application.


 Android Android
 Android Android

Download Code

You can download the full source code from GitHub. If you like this tutorial, star it in GitHub.