Automatically Mail send in Background in Android

11,056

Solution 1

MainActivity.java

Put on button click::

String fromEmail = "[email protected]";
                            String fromPassword = "xxxxxx";
                            String toEmails = [email protected];
                            String adminEmail = "[email protected]";
                            String emailSubject = "App Registration Mail";
                            String adminSubject = "App Registration Mail";
                            String emailBody = "Your message";
                            String adminBody = "Your message";
                            new SendMailTask(YOurActivity.this).execute(fromEmail,
                                    fromPassword, toEmails, emailSubject, emailBody);

GMail.java

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

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

import android.app.AlertDialog.Builder;
import android.util.Log;

public class GMail {

    final String emailPort = "587";// gmail's smtp port
    final String smtpAuth = "true";
    final String starttls = "true";
    final String emailHost = "smtp.gmail.com";

    String fromEmail;
    String fromPassword;
    @SuppressWarnings("rawtypes")
    String toEmailList;
    String emailSubject;
    String emailBody;

    Properties emailProperties;
    Session mailSession;
    MimeMessage emailMessage;

    public GMail() {

    }

    @SuppressWarnings("rawtypes")
    public GMail(String fromEmail, String fromPassword,
            String toEmailList, String emailSubject, String emailBody) {
        this.fromEmail = fromEmail;
        this.fromPassword = fromPassword;
        this.toEmailList = toEmailList;
        this.emailSubject = emailSubject;
        this.emailBody = emailBody;

        emailProperties = System.getProperties();
        emailProperties.put("mail.smtp.port", emailPort);
        emailProperties.put("mail.smtp.auth", smtpAuth);
        emailProperties.put("mail.smtp.starttls.enable", starttls);
        Log.i("GMail", "Mail server properties set.");
    }

    public MimeMessage createEmailMessage() throws AddressException,
            MessagingException, UnsupportedEncodingException {

        mailSession = Session.getDefaultInstance(emailProperties, null);
        emailMessage = new MimeMessage(mailSession);

        emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));

            Log.i("GMail","toEmail: "+toEmailList);
            emailMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(toEmailList));


        emailMessage.setSubject(emailSubject);
        emailMessage.setContent(emailBody, "text/html");// for a html email
        // emailMessage.setText(emailBody);// for a text email
        Log.i("GMail", "Email Message created.");
        return emailMessage;
    }

    public void sendEmail() throws AddressException, MessagingException {

        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromEmail, fromPassword);
        Log.i("GMail","allrecipients: "+emailMessage.getAllRecipients());
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        Log.i("GMail", "Email sent successfully.");

    }


}

SendMailTask.java:

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.os.AsyncTask;
import android.util.Log;

@SuppressWarnings("rawtypes")
public class SendMailTask extends AsyncTask {

    private ProgressDialog statusDialog;
    private Activity sendMailActivity;

    public SendMailTask(Activity activity) {
        sendMailActivity = activity;

    }

    protected void onPreExecute() {
        statusDialog = new ProgressDialog(sendMailActivity);
        statusDialog.setMessage("Getting ready...");
        statusDialog.setIndeterminate(false);
        statusDialog.setCancelable(false);
        statusDialog.show();
    }

    @SuppressWarnings("unchecked")
    @Override
    protected Object doInBackground(Object... args) {
        try {
            Log.i("SendMailTask", "About to instantiate GMail...");
            publishProgress("Processing input....");
            GMail androidEmail = new GMail(args[0].toString(),
                    args[1].toString(),  args[2].toString(), args[3].toString(),
                    args[4].toString());
            publishProgress("Preparing mail message....");
            androidEmail.createEmailMessage();
            publishProgress("Sending email....");
            androidEmail.sendEmail();
            publishProgress("Email Sent.");
            Log.i("SendMailTask", "Mail Sent.");

            Config.mailSuccess="1";


        } catch (Exception e) {
            publishProgress(e.getMessage());
            Log.e("SendMailTask", e.getMessage(), e);
        }
        return null;
    }

    @Override
    public void onProgressUpdate(Object... values) {
        statusDialog.setMessage(values[0].toString());

    }

    @Override
    public void onPostExecute(Object result) {
        statusDialog.dismiss();
    }


}

Library files

Solution 2

You need to import lib BackgroundMailLibrary

 BackgroundMail bm = new BackgroundMail(PasswordChangeActivity.this);
                                            bm.setGmailUserName(mail id);
                                            bm.setGmailPassword(Utils.decryptIt(password)); 
                                            bm.setMailTo(ownerEmail);
                                            bm.setFormSubject(subject);
                                            bm.setFormBody(body);
                                            bm.send();

Solution 3

mail send from background...

you can use javaMail to send mail from background
first of all you need to add these three .jar file...
Download these jar files

(1) Activation.jar: http://www.java2s.com/Code/Jar/a/Downloadactivationjar.htm
(2) Additionnal.jar: http://code.google.com/p/javamail-android/downloads/detail?name=additionnal.jar&can=2&q=
(3) mail.jar: http://www.java2s.com/Code/Jar/m/Downloadmailjar.htm

And then use these below code:
MainActivity.java

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

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

public class MainActivity extends Activity{

    EditText email_to,subjectEdit,messageEdit;
    Button mailButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initialize();

        mailButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                sendMail();
            }
        });

    }
     private void initialize() {
        email_to=(EditText)findViewById(R.id.editText_to);
        subjectEdit=(EditText)findViewById(R.id.editText_Subject);
        messageEdit=(EditText)findViewById(R.id.editText_Message);

        mailButton=(Button)findViewById(R.id.btn_SendMail);

    }
    protected void sendMail() {
            final String username = "Your Gmail Id ";
            final String password = "Your Gmail password";

            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");

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

            try {

                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(username));
                message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email_to.getText().toString()));
                message.setSubject("Sent from MobileApp" + subjectEdit.getText().toString());
                message.setText("Message : ,"
                    + "\n\n"+ messageEdit.getText().toString());

                new SendMailTask().execute(message);

              }catch (MessagingException mex) {
                 mex.printStackTrace();
              }


}

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

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



        @Override
        protected String doInBackground(Message... messages) {
            try {
                Transport.send(messages[0]);
                return "Success";
            } 
            catch(SendFailedException ee)
            {
                if(progressDialog.isShowing())
                    progressDialog.dismiss();
                return "error1";
            }catch (MessagingException e) {
                if(progressDialog.isShowing())
                    progressDialog.dismiss();
                return "error2";
            }

        }


        @Override
        protected void onPostExecute(String result) {
            if(result.equals("Success"))
            {

                super.onPostExecute(result);
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, "Mail Sent Successfully", Toast.LENGTH_LONG).show();

            subjectEdit.setText("");
            messageEdit.setText("");
            }
            else
            if(result.equals("error1"))
                Toast.makeText(MainActivity.this, "Email Failure", Toast.LENGTH_LONG).show();
            else
                if(result.equals("error2"))
                    Toast.makeText(MainActivity.this, "Email Sent problem2", Toast.LENGTH_LONG).show();

        }
    }
}


activity_main.xml

<LinearLayout 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:orientation="vertical"
    tools:context="com.example.ar.MainActivity" >

    <EditText
        android:id="@+id/editText_to"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="To " >

        <requestFocus
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </EditText>
    <EditText
        android:id="@+id/editText_Subject"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Subject" >


    </EditText>

    <EditText
        android:id="@+id/editText_Message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Message" />

    <Button
        android:id="@+id/btn_SendMail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Mail" />

</LinearLayout>


AndroidManifest.xml
Add this permission only...

<uses-permission android:name="android.permission.INTERNET" />
Share:
11,056
Nabeel Hafeez
Author by

Nabeel Hafeez

Updated on August 01, 2022

Comments

  • Nabeel Hafeez
    Nabeel Hafeez almost 2 years

    When I press on Send Button in log show Mail Sent But Actually mail not sent. Please help me my code below. Why Mail not sent?

    GMailSender.java

    package com.example.sendmail;
    
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.Multipart;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    
    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;
    
        private Multipart _multipart = new MimeMultipart();
        static {
            Security.addProvider(new com.example.sendmail.JSSEProvider());
        }
    
        public GMailSender(String user, 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.setProperty("mail.smtp.quitwait", "false");
    
            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 {
            try {
                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);
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                _multipart.addBodyPart(messageBodyPart);
    
                // Put parts in message
                message.setContent(_multipart);
                if (recipients.indexOf(',') > 0)
                    message.setRecipients(Message.RecipientType.TO,
                            InternetAddress.parse(recipients));
                else
                    message.setRecipient(Message.RecipientType.TO,
                            new InternetAddress(recipients));
                Transport.send(message);
            } catch (Exception e) {
    
            }
        }
    
        public void addAttachment(String filename) throws Exception {
            BodyPart messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName("download image");
    
            _multipart.addBodyPart(messageBodyPart);
        }
    
        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");
            }
        }
    }
    

    JSSEProvider.java

    package com.example.sendmail;
    
    import java.security.AccessController;
    import java.security.Provider;
    
    public final 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;
                        }
                    });
        }
    }
    

    MainActivity.java

    package com.example.sendmail;
    
    import android.os.Bundle;
    import android.os.Environment;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
     public class MainActivity extends Activity {
        Button send;
    //String filename = "/sdcard/mysdfile";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            send = (Button) findViewById(R.id.send);
            send.setOnClickListener(new View.OnClickListener() {
    
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    new Thread(new Runnable() {
                        @SuppressLint("SdCardPath") public void run() {
                            try {
                                GMailSender sender = new GMailSender("[email protected]","**password***");
                                ///Toast.makeText(getApplicationContext(), "Connect", Toast.LENGTH_LONG).show();
                                //sender.addAttachment(filename);
                                sender.addAttachment(Environment.getExternalStorageDirectory().getPath()+"/sdcard/mysdfile.txt");
                                sender.sendMail("Test mail", "This mail has been sent from android app along with attachment","[email protected]",
                                        "[email protected]");
    
                                Log.i("Mail", "Sent");
                                //Toast.makeText(getApplicationContext(),"Your mail has been sent",Toast.LENGTH_LONG).show();
    
    
                            } catch (Exception e) {
                                runOnUiThread(new Runnable() 
                                {
                                    public void run() 
                                    {
                                        Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();    
                                    }
                                }); 
    
                                Log.i("Mail", "Failed"+e);
                                //Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
    
                            }
                        }
                    }).start();
    
                    send.setText("Ok");
                }
            });
    
        }
    
    }
    

    no error appear and not send mail in sender mail and no mail in receiver mail inbox.

  • Nabeel Hafeez
    Nabeel Hafeez about 9 years
    (github.com/kristijandraca/BackgroundMailLibrary) I am download library from that link but not add in my project. please tell me. How to add in my project for use Background Mail.
  • Nabeel Hafeez
    Nabeel Hafeez about 9 years
    I add that three libraries. activation.jar additionnal.jar mail.jar
  • Nabeel Hafeez
    Nabeel Hafeez about 9 years
    error in Config.mailSuccess="1"; when import config java util then error on mail success.
  • Nabeel Hafeez
    Nabeel Hafeez about 9 years
    Please send the code for attach file from phone memory or external memory.
  • vijay
    vijay about 9 years
    tutorialsbuzz.com/2014/02/… try this links code if it not working tell me i will tell how to do..
  • vijay
    vijay about 9 years
    Dont forget to add this line to your manifest <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • Nabeel Hafeez
    Nabeel Hafeez about 9 years
    Any function about attach file from phone memory.
  • Abdul Rizwan
    Abdul Rizwan about 9 years
    You can refer the following link , and use import option...stackoverflow.com/a/29892730/3636561
  • Nabeel Hafeez
    Nabeel Hafeez about 9 years
    That above links are not helpful. Because I save file through filling successfully now i want it attach automatically without user interaction.
  • Nabeel Hafeez
    Nabeel Hafeez about 9 years
  • dsb
    dsb about 7 years
    @NabeelHafeez what do you mean by "when import config java util then error on mail success"? how did you fix this problem?
  • Nabeel Hafeez
    Nabeel Hafeez almost 7 years
    I remove config.mailSuccess = 1; then work perfectly.
  • QWERTY
    QWERTY almost 7 years
    @vijay Hey do you have any idea why it does not send to my gmail?
  • Geet Thakur
    Geet Thakur over 5 years
    I got this error every time. javax.mail.AuthenticationFailedException err: at javax.mail.Service.connect(Service.java:319) err: at javax.mail.Service.connect(Service.java:169) err: at com.hwl.common.emailsend.GMail.sendEmail(GMail.java:80) err: at com.hwl.common.ExceptionHandler$1.run(ExceptionHandler.java:‌​97)