Java Mail API using GMAIL OAuth API in Android

Java Mail API using GMAIL OAuth API in Android
Hello friends, In this post, I will show how to send mail with GMail using OAuth2.0 in Android. This Project contains a lot of steps like Permission, Google Play Service check to do.
So, please download the project to perform GMail API completely.

First of All, we have to generate OAuth key in Google API Console. To Generate OAuth Key, use your SHA1 key and your app's Package Name as in your Manifest.Paste Following code in your Command Prompt to get SHA1 key in Windows
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Project Structure

Create a new Project in Android Studio with the required Specifications.

AndroidManifest.xml

Don't forget to add the following permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<!--Added for Accessing External Storage-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
We have to add the following Jar Files into your Project as like Normal Java Mail API.
  1. mail.jar
  2. activation.jar
  3. additionnal.jar
Download Jars From Server

build.gradle

Open your app level build.gradle file add the following lines.
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.google.android.gms:play-services-identity:8.4.0'
    compile('com.google.api-client:google-api-client-android:1.22.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile('com.google.apis:google-api-services-gmail:v1-rev44-1.22.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile files('libs/mail.jar')
    compile files('libs/activation.jar')
    compile files('libs/additionnal.jar')
}
Initialize the Google API Client as in the following.
GoogleAccountCredential mCredential;
String[] SCOPES = {
    GmailScopes.GMAIL_LABELS,
    GmailScopes.GMAIL_COMPOSE,
    GmailScopes.GMAIL_INSERT,
    GmailScopes.GMAIL_MODIFY,
    GmailScopes.GMAIL_READONLY,
    GmailScopes.MAIL_GOOGLE_COM
};
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
  getApplicationContext(), Arrays.asList(SCOPES))
  .setBackOff(new ExponentialBackOff());
Following line is used to start Account Pick in Android
// Start a dialog from which the user can choose an account
startActivityForResult(mCredential.newChooseAccountIntent(), Utils.REQUEST_ACCOUNT_PICKER);
Use the following code to generate and initialize all the processes regarding this project.
// Async Task for sending Mail using GMail OAuth
    private class MakeRequestTask extends AsyncTask {
        private com.google.api.services.gmail.Gmail mService = null;
        private Exception mLastError = null;
        private View view = sendFabButton;

        public MakeRequestTask(GoogleAccountCredential credential) {
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.gmail.Gmail.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName(getResources().getString(R.string.app_name))
                    .build();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                return getDataFromApi();
            } catch (Exception e) {
                mLastError = e;
                cancel(true);
                return null;
            }
        }

        private String getDataFromApi() throws IOException {
            // getting Values for to Address, from Address, Subject and Body
            String user = "me";
            String to = Utils.getString(edtToAddress);
            String from = mCredential.getSelectedAccountName();
            String subject = Utils.getString(edtSubject);
            String body = Utils.getString(edtMessage);
            MimeMessage mimeMessage;
            String response = "";
            try {
                mimeMessage = createEmail(to, from, subject, body);
                response = sendMessage(mService, user, mimeMessage);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return response;
        }

        // Method to send email
        private String sendMessage(Gmail service,
                                   String userId,
                                   MimeMessage email)
                throws MessagingException, IOException {
            Message message = createMessageWithEmail(email);
            // GMail's official method to send email with oauth2.0
            message = service.users().messages().send(userId, message).execute();

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

        // Method to create email Params
        private 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);
            InternetAddress tAddress = new InternetAddress(to);
            InternetAddress fAddress = new InternetAddress(from);

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

            // Create Multipart object and add MimeBodyPart objects to this object
            Multipart multipart = new MimeMultipart();

            // Changed for adding attachment and text
            // This line is used for sending only text messages through mail
            // email.setText(bodyText);

            BodyPart textBody = new MimeBodyPart();
            textBody.setText(bodyText);
            multipart.addBodyPart(textBody);

            if (!(activity.fileName.equals(""))) {
                // Create new MimeBodyPart object and set DataHandler object to this object
                MimeBodyPart attachmentBody = new MimeBodyPart();
                String filename = activity.fileName; // change accordingly
                DataSource source = new FileDataSource(filename);
                attachmentBody.setDataHandler(new DataHandler(source));
                attachmentBody.setFileName(filename);
                multipart.addBodyPart(attachmentBody);
            }

            // Set the multipart object to the message object
            email.setContent(multipart);
            return email;
        }

        private 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;
        }

        @Override
        protected void onPreExecute() {
            mProgress.show();
        }

        @Override
        protected void onPostExecute(String output) {
            mProgress.hide();
            if (output == null || output.length() == 0) {
                showMessage(view, "No results returned.");
            } else {
                showMessage(view, output);
            }
        }

        @Override
        protected void onCancelled() {
            mProgress.hide();
            if (mLastError != null) {
                if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
                    showGooglePlayServicesAvailabilityErrorDialog(
                            ((GooglePlayServicesAvailabilityIOException) mLastError)
                                    .getConnectionStatusCode());
                } else if (mLastError instanceof UserRecoverableAuthIOException) {
                    startActivityForResult(
                            ((UserRecoverableAuthIOException) mLastError).getIntent(),
                            Utils.REQUEST_AUTHORIZATION);
                } else {
                    showMessage(view, "The following error occurred:\n" + mLastError.getMessage());
                    Log.v("Error", mLastError.getMessage());
                }
            } else {
                showMessage(view, "Request Cancelled.");
            }
        }
    }

Screens:

Screen1
Screen2
Screen3
Screen4
Screen5

Important

You should add the following lines in proguard while releasing your APK
-keep class com.google.** 
Thanks to Kaba Droid42 for this.

Download Source Code

You can download the full source from the following Github link. If you Like this library, Please star it in Github.

Share this

Related Posts

Previous
Next Post »

18 comments

comments
19 July 2016 at 00:02 delete

Hello! Thanks for sharing. That’s exactly what I need and it runs successfully. However, I still can't understand how you list all items that need to be agreed by users (The second Screenshot you post on the web). Could you let me know how to solve it or which part of codes in Main Activity I can figure out? Thank you very much.

Reply
avatar
19 July 2016 at 18:36 delete

Actually, it is a built-in screen in the gmail-sdk and thanks for your comment

Reply
avatar
25 August 2016 at 19:52 delete

Hello! I have a question about the code.
It works very well only if I login with my account, which already generated OAuth Key.
When I login with other accounts,
"message = service.users().messages().send(userId, message).execute();"
will throw UserRecoverableAuthException: NeedPermission
How can I do to fix this problem?
Thank you very much!

Reply
avatar
3 January 2017 at 00:23 delete

I get an error: The following error occured: 403 Forbidden...
How can I fix this?

Reply
avatar
3 January 2017 at 21:41 delete

Are you enabled the Gmail API in your Google API Console ?

Reply
avatar
3 January 2017 at 21:42 delete

If not enable it and try again.

Reply
avatar
16 March 2017 at 20:01 delete

Hello...
I followed your tutorial (compliments for this, very useful) I don't have problem if i use the SHA1 from my debugkeystore but, when i sign my apk for release and I put the SHA1 fingerprint in my API Manager Console, my app does not send email. No error on console, no error from my app it just stops sending email.

Thank you for any help

Reply
avatar
22 March 2017 at 14:51 delete

Ok, after a series of tests the problem is... ProGuard. If the value minifyEnabled in the build.gradle is true the email sender doesn't work, if in false all work.
Any idea why?

Reply
avatar
22 March 2017 at 18:15 delete

in the proguard-rules.pro use
-keep class com.google.** {*;}
instead
-keep class com.google.**
and all work! :)

Reply
avatar
10 May 2017 at 22:08 delete

I have download your project and build it in android studio after successfully run when I send mail It just crushes.

Reply
avatar
11 May 2017 at 21:58 delete

Will you explain it clearly bro ? Please

Reply
avatar
29 May 2017 at 12:33 delete

Thanks for you reply. I have solved my problem :)

Reply
avatar
Geary
11 July 2017 at 13:32 delete

Hi, your code works excellent and it helped me alot.... but can you please tell me about image sharing using this code ?... if so, i would help me alot mate :)

Reply
avatar
16 July 2017 at 20:56 delete

Dear Geary,

I have updated the post with sending mail with attachment.

Thanks for your support and Keep on visiting Androidmads

Reply
avatar
24 July 2017 at 17:36 delete

Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
java training in chennai |
java training institutes in chennai

Reply
avatar
18 August 2017 at 08:42 delete

I don't have REQUEST_ACCOUNT_PICKER in my Utils class in my android studio ..

Reply
avatar

Please Comment about the Posts and Blog