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 the OAuth key in
Google API Console and to generate the OAuth key, you need SHA1 Key.
Steps
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
- Open Google API Console and create a new project in your Dashboard.
- Click Enable APIS and Services and go to API Page. Then select Gmail API and select “Enable API”.
- Then select Credentials in the side menu and select “Create Credentials” in the Credentials Tab. And Select “OAuth Client ID” as shown in the screen.
- Then select “Android” and Paste your SHA1 Key generated in the previous step & Package Name of your Application.
- 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.
- Creating a New Project with Android Studio
- Setting up AndroidManifest for the project
- Setting up Gmail and Java mail API.
- Implementation of the functionality.
Without any more introduction, we will jump into the coding part.
Creating New Projects with Android Studio
- Open Android Studio and Select Create a new project.
- Name the project as per your wish and select your activity template.
- Click the “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.
- <uses-permission android:name="android.permission.INTERNET"/>
- <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.
- dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
- compile 'com.android.support:appcompat-v7:25.0.1'
- compile 'com.google.android.gms:play-services-auth:11.8.0'
- compile('com.google.api-client:google-api-client-android:1.23.0') {
- exclude group: 'org.apache.httpcomponents'
- }
- compile('com.google.apis:google-api-services-gmail:v1-rev82-1.23.0') {
- exclude group: 'org.apache.httpcomponents'
- }
- compile files('libs/mail.jar')
- compile files('libs/activation.jar')
- compile files('libs/additionnal.jar')
- }
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.
-
- mCredential = GoogleAccountCredential.usingOAuth2(
- getApplicationContext(), Arrays.asList(SCOPES))
- .setBackOff(new ExponentialBackOff());
- Here “SCOPES” is the array used to specify the scope for your application.
- private static final String[] SCOPES = {
- GmailScopes.GMAIL_LABELS,
- GmailScopes.GMAIL_COMPOSE,
- GmailScopes.GMAIL_INSERT,
- GmailScopes.GMAIL_MODIFY,
- GmailScopes.GMAIL_READONLY,
- GmailScopes.MAIL_GOOGLE_COM
- };
- The following line is used to start Account Pick in Android.
-
- startActivityForResult(mCredential.newChooseAccountIntent(), Utils.REQUEST_ACCOUNT_PICKER);
Method to send Mail
-
- private String 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());
- return message.getId();
- }
Method to Create Email with Attachment
- 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);
-
-
- Multipart multipart = new MimeMultipart();
-
-
-
-
-
- BodyPart textBody = new MimeBodyPart();
- textBody.setText(bodyText);
- multipart.addBodyPart(textBody);
-
- if (!(activity.fileName.equals(""))) {
-
- MimeBodyPart attachmentBody = new MimeBodyPart();
- String filename = activity.fileName;
- DataSource source = new FileDataSource(filename);
- attachmentBody.setDataHandler(new DataHandler(source));
- attachmentBody.setFileName(filename);
- multipart.addBodyPart(attachmentBody);
- }
-
-
- 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;
- }
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.
- <!--Added for Accessing External Storage-->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Note
- You should add the following lines in proguard while releasing your APK.
keep class com.google.**
- You should add separate SHA1 Key for Debug and Release mode for your application.
DEMO
Download Code
You can download the full source code from GitHub. If you like this tutorial, star it in GitHub.