articles

Home / DeveloperSection / Articles / Sending mail without user interaction in Android

Sending mail without user interaction in Android

Sending mail without user interaction in Android

Manoj Pandey50735 18-Mar-2015

Sending mail without user interaction in Android

You have learned Android Intent, which is an object carrying an intent ie. message from one component to another component within 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 an 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 an 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 an example of send email without the interaction of the user in android

  • Create an android project and SDK must be greater than 10
  • Download three jar file
    • mail.jar
    • activation.jar
    • additionnal.jar
  • Add jar file in your libs folder and add it in the build path.
  • 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>

 Add the 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();

           }      } }

Create class GMailSender, java and extends javax.mail.Authenticator. You are able to use any package name.  For this extends, you need to add these 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");

                                }

                }

}

 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 

Sending mail without user interaction in Android


Updated 22-May-2020

Leave Comment

Comments

Liked By