Sunday, 6 October 2013

Send mail from Android application without using default/built-in application

We know, We can send an e-mail using Intents, This will invoke either default mail app or built-in device mail apps to send an e-mail. This is unnecessary for user to work on e-mail application while he is trying to work an our application. So the question is
how to send an e-mail from android application without user interaction?
Answer is you can achieve this using JavaMail API.
You have to use following three jars.
  1. mail.jar
  2. activation.jar
  3. additionnal.jar
Complete code:

MainActivity.java

package com.exmple.javamail;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MainActivity extends Activity {
 private static String username = "";
 private static String password = "";
 private static String name = "";
 private EditText mRecEmailEdit;
 private EditText mSubjectEdit;
 private EditText mMessageEdit;
 private EditText mNameEdit;
 private EditText mEmailEdit;
 private EditText mPasswordEdit;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mNameEdit = (EditText) findViewById(R.id.sender_name);
  mEmailEdit = (EditText) findViewById(R.id.sender_email);
  mPasswordEdit = (EditText) findViewById(R.id.sender_password);
  mRecEmailEdit = (EditText) findViewById(R.id.email);
  mSubjectEdit = (EditText) findViewById(R.id.subject);
  mMessageEdit = (EditText) findViewById(R.id.message);
  Button sendButton = (Button) findViewById(R.id.send);

  sendButton.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    name = mNameEdit.getText().toString();
    username = mEmailEdit.getText().toString();
    password = mPasswordEdit.getText().toString();
    String email = mRecEmailEdit.getText().toString();
    String subject = mSubjectEdit.getText().toString();
    String message = mMessageEdit.getText().toString();
    sendMail(email, subject, message);
   }
  });
 }

 private void sendMail(String email, String subject, String messageBody) {
  Session session = createSessionObject();

  try {
   Message message = createMessage(email, subject, messageBody,
     session);
   new SendMailTask().execute(message);
  } catch (AddressException e) {
   e.printStackTrace();
  } catch (MessagingException e) {
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
 }

 private Message createMessage(String email, String subject,
   String messageBody, Session session) throws MessagingException,
   UnsupportedEncodingException {
  Message message = new MimeMessage(session);
  message.setFrom(new InternetAddress(username, name));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(
    email, email));
  message.setSubject(subject);
  message.setText(messageBody);
  return message;
 }

 private Session createSessionObject() {
  Properties properties = new Properties();
  properties.put("mail.smtp.auth", "true");
  properties.put("mail.smtp.starttls.enable", "true");
  properties.put("mail.smtp.host", "smtp.gmail.com");
  properties.put("mail.smtp.port", "587");

  return Session.getInstance(properties, new javax.mail.Authenticator() {
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password);
   }
  });
 }

 private class SendMailTask extends AsyncTask<Message, Void, Void> {
  private ProgressDialog progressDialog;

  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   progressDialog = ProgressDialog.show(MainActivity.this,
     "Please wait", "Sending mail", true, false);
  }

  @Override
  protected void onPostExecute(Void aVoid) {
   super.onPostExecute(aVoid);
   progressDialog.dismiss();
  }

  @Override
  protected Void doInBackground(Message... messages) {
   try {
    Transport.send(messages[0]);
    runOnUiThread(new Runnable() {

     @Override
     public void run() {
      Toast.makeText(MainActivity.this,
        "Mail sent successfully", Toast.LENGTH_LONG)
        .show();
     }
    });
   } catch (final MessagingException e) {
    e.printStackTrace();
    runOnUiThread(new Runnable() {

     @Override
     public void run() {
      Toast.makeText(MainActivity.this,
        e.getClass() + " : " + e.getMessage(),
        Toast.LENGTH_LONG).show();
     }
    });
   }
   return null;
  }
 }
}


activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/sender_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:hint="your Name"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/sender_email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/sender_name"
        android:ems="10"
        android:hint="your e-mail"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/sender_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/email"
        android:inputType="textPassword"
        android:layout_below="@+id/sender_email"
        android:hint="Your e-mail password" />

    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/sender_password"
        android:ems="10"
        android:hint="reciever e-mail"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/subject"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/email"
        android:layout_below="@+id/email"
        android:hint="subject" />

    <EditText
        android:id="@+id/message"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/subject"
        android:ems="10"
        android:hint="message"
        android:inputType="textMultiLine"
        android:lines="5" />

    <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/message"
        android:text="Send!" />

</RelativeLayout>




Complete code as zip on GITHUB

I hope this post is useful. kindly share your feedback as comment here.


Thank You