Sending mail without user interaction

You have learnt Android Intent, which is an object carrying an intent ie. message from one component to another component with-in the application or outside the application.

As such you do not need to develop your email client from scratch because they are already available like Gmail and K9mail. But you will need to send email from your Android application, where you will have to write an Activity that needs to launch an email client and sends an email using your Android device. For this purpose, your Activity will send an ACTION_SEND along with appropriate data load, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your email data.

Here I am creating example of send email without interaction of user in android

1.      Create an android project and sdk must be greater than 10

2.      Download three jar file

·         mail.jar

·         activation.jar

·         additionnal.jar

3.    Add jar file in your libs folder and add it in build path.

4.    Add permission in AndroidManifest.xml file

 

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.androimail"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="18" />

 

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

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.example.androimail.MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

               <action android:name="android.intent.action.MAIN" />

 

       <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

</manifest>

 

5.      Add following code in MainActicvity.class

 

package com.example.androimail;

 

import android.os.AsyncTask;

import android.os.Build;

import android.os.Bundle;

import android.os.StrictMode;

import android.annotation.SuppressLint;

import android.annotation.TargetApi;

import android.app.Activity;

import android.app.ProgressDialog;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

 

public class MainActivity extends Activity {

     Button button;

     GMailSender sender;

 

     @SuppressLint("NewApi")

     @TargetApi(Build.VERSION_CODES.GINGERBREAD)

     @Override

     protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           setContentView(R.layout.activity_main);

           button = (Button) findViewById(R.id.mybtn);

      // Add your mail Id and Password

           sender = new GMailSender("my mail", "my password");

 

  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.

Builder().permitAll().build();

 

           StrictMode.setThreadPolicy(policy);

           button.setOnClickListener(new OnClickListener() {

 

                @Override

                public void onClick(View v) {

                     // TODO Auto-generated method stub

 

                     try {

                           new MyAsyncClass().execute();

 

                     } catch (Exception ex) {

  Toast.makeText(getApplicationContext(), ex.toString(), 100).show();

                     }

 

                }

           });

 

     }

 

     @Override

     public boolean onCreateOptionsMenu(Menu menu) {

       // Inflate the menu; this adds items to the action bar if it // is present.

           getMenuInflater().inflate(R.menu.main, menu);

           return true;

     }

 

     class MyAsyncClass extends AsyncTask<Void, Void, Void> {

 

           ProgressDialog pDialog;

 

           @Override

           protected void onPreExecute() {

                super.onPreExecute();

 

                pDialog = new ProgressDialog(MainActivity.this);

                pDialog.setMessage("Please wait...");

                pDialog.show();

 

           }

 

           @Override

           protected Void doInBackground(Void... mApi) {

                try {

       // Add subject, Body, your mail Id, and receiver mail Id.

       sender.sendMail("Subject", " body", "from Mail", "to mail");

  

 

                }

 

                catch (Exception ex) {

 

                }

                return null;

           }

 

           @Override

           protected void onPostExecute(Void result) {

                super.onPostExecute(result);

                pDialog.cancel();

Toast.makeText(getApplicationContext(), "Email send", 100).show();

           }

     }

}

6.      Create class GMailSender,java and extends javax.mail.Authenticator. You able to use any package name.  For this extends, you need to add this three jar in your project libraries.

Add following code

 

package com.example.androimail;

 

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.mail.Message;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import java.io.ByteArrayInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.security.Security;

import java.util.Properties;

 

public class GMailSender extends javax.mail.Authenticator {

                private String mailhost = "smtp.gmail.com";

                private String user;

                private String password;

                private Session session;

 

                static {

                                Security.addProvider(new JSSEProvider());

                }

 

                public GMailSender(final String user, final String password) {

                                this.user = user;

                                this.password = password;

 

                                Properties props = new Properties();

                                props.setProperty("mail.transport.protocol", "smtp");

                                props.setProperty("mail.host", mailhost);

                                props.put("mail.smtp.auth", "true");

                                props.put("mail.smtp.port", "465");

                                props.put("mail.smtp.socketFactory.port", "465");

                                props.put("mail.smtp.socketFactory.class",

                                                                "javax.net.ssl.SSLSocketFactory");

                                props.put("mail.smtp.socketFactory.fallback", "false");

                                props.put("mail.smtp.starttls.enable", "true");

 

                                props.setProperty("mail.smtp.quitwait", "false");

                             session = Session.getInstance(props, new javax.mail.Authenticator() {

                                             protected PasswordAuthentication getPasswordAuthentication() {

                                                                return new PasswordAuthentication(user, password);

                                                }

                                });

                                session = Session.getDefaultInstance(props, this);

                }

 

                protected PasswordAuthentication getPasswordAuthentication() {

                                return new PasswordAuthentication(user, password);

                }

 

                public synchronized void sendMail(String subject, String body,

                                                String sender, String recipients) throws Exception {

                                MimeMessage message = new MimeMessage(session);

                                DataHandler handler = new DataHandler(new ByteArrayDataSource(

                                                                body.getBytes(), "text/plain"));

                                message.setSender(new InternetAddress(sender));

                                message.setSubject(subject);

                                message.setDataHandler(handler);

 

                                if (recipients.indexOf(',') > 0)

                                                message.setRecipients(Message.RecipientType.TO,

                                                                                InternetAddress.parse(recipients));

                                else

                                 message.setRecipient(Message.RecipientType.TO, new InternetAddress(

                                                                                recipients));

                                Transport.send(message);

                }

 

                public class ByteArrayDataSource implements DataSource {

                                private byte[] data;

                                private String type;

 

                                public ByteArrayDataSource(byte[] data, String type) {

                                                super();

                                                this.data = data;

                                                this.type = type;

                                }

 

                                public ByteArrayDataSource(byte[] data) {

                                                super();

                                                this.data = data;

                                }

 

                                public void setType(String type) {

                                                this.type = type;

                                }

 

                                public String getContentType() {

                                                if (type == null)

                                                                return "application/octet-stream";

                                                else

                                                                return type;

                                }

 

                                public InputStream getInputStream() throws IOException {

                                                return new ByteArrayInputStream(data);

                                }

 

                                public String getName() {

                                                return "ByteArrayDataSource";

                                }

 

                                public OutputStream getOutputStream() throws IOException {

                                                throw new IOException("Not Supported");

                                }

                }

}

 

 

 

7.      Create an JSSEProvider  class and paste following code

 

package com.example.androimail;

 

import java.security.AccessController;

import java.security.Provider;

 

public class JSSEProvider extends Provider {

     public JSSEProvider() {

           super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");

           AccessController

         .doPrivileged(new java.security.PrivilegedAction<Void>() {

                           public Void run() {

      put("SSLContext.TLS",              

           "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");

              put("Alg.Alias.SSLContext.TLSv1", "TLS");

     put("KeyManagerFactory.X509",

    "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");

     put("TrustManagerFactory.X509",

  "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");

                                return null;

                           }

                     });

     }

}

 

Now run your application

 

  Modified On Nov-20-2017 10:04:49 AM
  1. Thanks for the example. I need some more help to get it working.
    I get the following error:
    mybtn cannot be resolved or is not a field
    in the MainActivity.java file

    wim 

  1. I found the problem for the error message. In Activity_main.xml a button must be defined:
    <Button
           android:id="@+id/mybtn"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_marginTop="30dp"
           android:text="Mail" />

    Now when I start up the app, the email is not send. The toast message "Email send" does not appear on the screen.
    How can I see an error message to try to resolve this?

    wim

  1. Use    
     Toast.makeText(MainActivity.this, "Email send", 100) .show();// instead of getApplicationContext()
        
    Remove toast from here and use this code after cancel progress dialog

    @Override

               protected void onPostExecute(Void result) {

                    super.onPostExecute(result);

                    pDialog.cancel();

    Toast.makeText(MainActivity.this,"Email send",100).show();

               }      

  1. Thanks for your reply. The toast message email send does appear on the screen now. However, I don't receive the email. not in my inbox and also not in the spam box
  1. I have checked my code which are working correctly.

    I don't know you are giving right mail Id or password , but if you are giving right information then you have need to check your account security. May be you have find a mail from Google for check access your account. Now tell him this was you which are accessing google account.

  1. I have entered my gmail login id and password in this line:

    // Add your mail Id and Password

               sender = new GMailSender("my mail", "my password");

    and in this line:

    // Add subject, Body, your mail Id, and receiver mail Id.

              sender.sendMail("Subject", " body", "from Mail", "to mail");

    tried it both with and without the @gmail.com extention and no emails are received

    If I login in gmail.com with the same login id and password, I can send and receive an email.

    I did not find a mail from google to check my account, and cannot find any settings to turn on or off to allow this.

  1. I created a new gmail account, used that in the app, got the message from google to authorize less secure apps, turned the restriction off, tried it again, and I now receive the email.
    thanks for your help.
  1. package com.example.emailsender;

    import android.annotation.TargetApi;
    import android.app.Activity; 
    import android.os.Build;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends Activity {
    Button btS;
        GMailSender sender;
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btS = (Button)findViewById(R.id.btSend);
    btS.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
      
                    
                    GMailSender mailsender = new GMailSender("sample@gmail.com", "xxxxxxxx");

                    String[] toArr = { "recipient@gmail.com", "recipient@gmail.com" };
                    mailsender.set_to(toArr);
                    mailsender.set_from("sample@gmail.com");
                    mailsender.set_subject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
                    mailsender.setBody("Email body.");

                    try {
                        //mailsender.addAttachment("/sdcard/filelocation");

                        if (mailsender.send()) {
                            Toast.makeText(MainActivity.this,
                                    "Email was sent successfully.",
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Email was not sent.",
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        
                        Log.e("MailApp", "Could not send email", e);
                    }
                }
    });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }       

    }

  1. here is the error from logCat

    06-19 05:59:03.072: E/AndroidRuntime(5479): FATAL EXCEPTION: AsyncTask #2

    06-19 05:59:03.072: E/AndroidRuntime(5479): Process: com.example.disapp, PID: 5479

    06-19 05:59:03.072: E/AndroidRuntime(5479): java.lang.RuntimeException: An error occured while executing doInBackground()

    06-19 05:59:03.072: E/AndroidRuntime(5479): at android.os.AsyncTask$3.done(AsyncTask.java:300)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at java.util.concurrent.FutureTask.run(FutureTask.java:242)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at java.lang.Thread.run(Thread.java:841)

    06-19 05:59:03.072: E/AndroidRuntime(5479): Caused by: java.lang.NoClassDefFoundError: javax.activation.DataHandler

    06-19 05:59:03.072: E/AndroidRuntime(5479): at com.example.disapp.GMailSender.sendMail(GMailSender.java:59)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at com.example.disapp.Home$MyAsyncClass.doInBackground(Home.java:416)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at com.example.disapp.Home$MyAsyncClass.doInBackground(Home.java:1)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at android.os.AsyncTask$2.call(AsyncTask.java:288)

    06-19 05:59:03.072: E/AndroidRuntime(5479): at java.util.concurrent.FutureTask.run(FutureTask.java:237)

    06-19 05:59:03.072: E/AndroidRuntime(5479): ... 4 more

    06-19 05:59:03.092: W/ActivityManager(373):   Force finishing activity com.example.disapp/.Home

  1. First of all, thanks for taking the time to write this amazing tutorial!

    My problem is that no email is recieved (unsafe apps enabled and two-step auth disabled).
    sender = new GMailSender(email.getText().toString().toLowerCase(), password.getText().toString());
    Also inside MyAsyncClass class I wrote:
    private String mails = email.getText().toString().toLowerCase();
    private String mailto = recipient.getText().toString().toLowerCase();
    To do:
    sender.sendMail("Subject", " body", mails,  mailto);
    I suppose this is valid, right?

    Even if I have no errors, no email is recieved :(
    Could you please help me? Thanks in advance
  1. Check your google account. If you have not received email then change your account security setting and make your gmail account secure less.
  1. Unfortunately my app has stppoed..what is the problem?
  1. Hi Sakshi you have need to check log file which is created automatically when app Unfortunately stopped.


  1. My app does not start, i run my app on bluestack, when i try to start the app it does not start or give any error message. what can i do to make it work?
  1. Hi Zeeshan jiwani Thanks for read my article.
       Please provide your code then I can help you. Full code is not important, you can provide only MainActivity.class code
  1.  Yes. It will be secure your password. Don't worry Sumit.
  1. Hello, I'm doing this in a Fragment. and when I hit the button, it stays on the "Please wait..." screen
  1.  Hi Teyim are you getting mail or not.  
    Use below code on doInBackground block. 
    You can find exception if founded any exception.

    @Override

               protected Void doInBackground(Void... mApi) {

                    try {

           // Add subject, Body, your mail Id, and receiver mail Id.

           sender.sendMail("Subject", " body", "from Mail", "to mail");

      

     

                    }

     

                    catch (Exception ex) {

    getActivity().runOnUiThread(new Runnable() { @Override pDialog.cancel();

    Toast.makeText(MainActivity.this,ex.getMessage(),100).show();


    } });

     

                    }

                    return null;

               }

  1. At first it asked for less secure permission but even after enabling it, email is not sent

Leave Comment