Langsung ke konten utama

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.

Komentar

Postingan populer dari blog ini

Android Tutorial: Use LeakCanary to detect memory leaks

Overview The memory leak can be a headache to detect and to resolve, small memory leaks can be hidden and may be seen after a long usage of the application and hunting memory leaks is not a simple task. In this tutorial we will create a leaked application and we will use the LeakCanary library to detect the memory leak. Step 1: add the LeakCanary dependency to the application Modify the app/build.gradle to add the LeakCanary dependency as follows: Step 2: Extend and configure the Application class We need to call LeakCanary.install in onCreate method: Step 3: Create a leaked activity For this we will create a singleton class that saves the context: Then, the main activity (leaked one), will use the singleton and then we'll go to a new activity: Then, in the new activity we'll call System.gc to force the garbage collector in order to accelerate the analysis. Step 4: Retrieve the analysis result A nice notification can be shown: The result can be retrieved from logcat: Source c...

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s...

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the ...