Tuesday 24 April 2012

Send Emails in Background in Android.without user interaction...



Step-1
First of all Download 3 Jar files from http://code.google.com/p/javamail-android/downloads/list. (Ref. "http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-android-a")
activation.jar
additional.jar
mail.jar

Step-2
copy and paste those jar files into your project. then
Integrate all above jar files into your project
Right click on your project --> Properties -->
Java Build path --> Libraries --> Add JARs--> Add all 3 jars

Now go to Next Tab "Order and Export"--> select all --> Ok

Step-3
Create one class

import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
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;

public class GMailSender extends javax.mail.Authenticator {
    private String _user;
      private String _pass;
   
      private String[] _to;
      private String _from;
   
      private String _port;
      private String _sport;
   
      private String _host;
   
      private String _subject;
      private String _body;
   
      private boolean _auth;
      
      private boolean _debuggable;
   
      private Multipart _multipart;
   
   
      public GMailSender() {
        _host = "smtp.gmail.com"; // default smtp server
        _port = "465"; // default smtp port
        _sport = "465"; // default socketfactory port
   
        _user = ""; // username
        _pass = ""; // password
        _from = ""; // email sent from
        _subject = ""; // email subject
        _body = ""; // email body
   
        _debuggable = false; // debug mode on or off - default off
        _auth = true; // smtp authentication - default on
   
        _multipart = new MimeMultipart();
   
        // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
        CommandMap.setDefaultCommandMap(mc);
      }
   
      public GMailSender(String user, String pass) {
        this();
   
        _user = user;
        _pass = pass;
      }
   
      public boolean send() throws Exception {
        Properties props = _setProperties();
   
        if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
          Session session = Session.getInstance(props, this);
   
          MimeMessage msg = new MimeMessage(session);
   
          msg.setFrom(new InternetAddress(_from));
          
          InternetAddress[] addressTo = new InternetAddress[_to.length];
          for (int i = 0; i < _to.length; i++) {
            addressTo[i] = new InternetAddress(_to[i]);
          }
            msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
   
          msg.setSubject(_subject);
          msg.setSentDate(new Date());
   
          // setup message body
          BodyPart messageBodyPart = new MimeBodyPart();
          messageBodyPart.setText(_body);
          _multipart.addBodyPart(messageBodyPart);
   
          // Put parts in message
          msg.setContent(_multipart);
   
          // send email
          Transport.send(msg);
   
          return true;
        } else {
          return false;
        }
      }
   
      public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
   
        _multipart.addBodyPart(messageBodyPart);
      }
   
      @Override
      public javax.mail.PasswordAuthentication getPasswordAuthentication() {
        return  new javax.mail.PasswordAuthentication(_user,_pass);
      }
   
      private Properties _setProperties() {
        Properties props = new Properties();
   
        props.put("mail.smtp.host", _host);
   
        if(_debuggable) {
          props.put("mail.debug", "true");
        }
   
        if(_auth) {
          props.put("mail.smtp.auth", "true");
        }
   
        props.put("mail.smtp.port", _port);
        props.put("mail.smtp.socketFactory.port", _sport);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
   
        return props;
      }
   
      // the getters and setters
      public String getBody() {
        return _body;
      }
   
      public void setBody(String _body) {
        this._body = _body;
      }

    public String[] get_to() {
        return _to;
    }

    public void set_to(String[] _to) {
        this._to = _to;
    }

    public String get_from() {
        return _from;
    }

    public void set_from(String _from) {
        this._from = _from;
    }

    public String get_subject() {
        return _subject;
    }

    public void set_subject(String _subject) {
        this._subject = _subject;
    }
   
    }


Step-4

in your Main class

public class GMailMain extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        Button addImage = (Button) findViewById(R.id.send);
        addImage.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
               
               
                GMailSender mailsender = new GMailSender("sender@gmail.com", "password123");

                String[] toArr = { "receiver1@gmail.com", "receiver2@gmail.com" };
                mailsender.set_to(toArr);
                mailsender.set_from("sender@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(GMailMain.this,
                                "Email was sent successfully.",
                                Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(GMailMain.this, "Email was not sent.",
                                Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                   
                    Log.e("MailApp", "Could not send email", e);
                }
            }
        });

    }
}

17 comments:

Anonymous said...

I did everything step by step as instructed by this post. However, I keep on getting the catch error ("could not send the email"). I have verified that every field has been validated and added the internet permission in the manifest but somehow, i'm still getting an error message. Any ideas why?

Unknown said...
This comment has been removed by the author.
Unknown said...

Hi .. It works fine without any errors..you have to replace sender@gmail.com with your gmail id and password123 to your own password and change the receiver1@gmail.com to the receivermailid .


Thanks to Ronak Pandya :)

Ronak Pandya said...

Thanks...keep visiting..

Unknown said...

I got this error.please help me to fix this problem

Could not send email
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Permission denied
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:310)

Unknown said...
This comment has been removed by the author.
Unknown said...

Hi am not set the internet permission on manifest file.so,only above error come.

Now,I get this error.please hel me
javax.mail.AuthenticationFailedException

Unknown said...

I found the answer. This is becuase of 2step verification on my google account.I turned off.Now,its works.Thanks for coding

Anonymous said...

Could not send email
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.jav at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getLocalHost(InetAddress.java:365)

Anonymous said...

i got this error pls help me ..pls..

Anonymous said...

i want to set body as a HTML tag in this email format,
so can you reply me for this.

Thank You

Anonymous said...

can anyone please help me ?
i have this error

05-22 00:58:02.083: E/MailApp(2890): Could not send email
05-22 00:58:02.083: E/MailApp(2890): android.os.NetworkOnMainThreadException
05-22 00:58:02.083: E/MailApp(2890): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156)
05-22 00:58:02.083: E/MailApp(2890): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-22 00:58:02.083: E/MailApp(2890): at java.net.InetAddress.getLocalHost(InetAddress.java:365)
05-22 00:58:02.083: E/MailApp(2890): at javax.mail.internet.InternetAddress.getLocalAddress(InternetAddress.java:517)
05-22 00:58:02.083: E/MailApp(2890): at javax.mail.internet.UniqueValue.getUniqueMessageIDValue(UniqueValue.java:99)
05-22 00:58:02.083: E/MailApp(2890): at javax.mail.internet.MimeMessage.updateMessageID(MimeMessage.java:2054)
05-22 00:58:02.083: E/MailApp(2890): at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2076)
05-22 00:58:02.083: E/MailApp(2890): at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2042)
05-22 00:58:02.083: E/MailApp(2890): at javax.mail.Transport.send(Transport.java:117)
05-22 00:58:02.083: E/MailApp(2890): at com.example.mail.GMailSender.send(GMailSender.java:106)
05-22 00:58:02.083: E/MailApp(2890): at com.example.mail.GMailMain$1.onClick(GMailMain.java:36)
05-22 00:58:02.083: E/MailApp(2890): at android.view.View.performClick(View.java:4633)
05-22 00:58:02.083: E/MailApp(2890): at android.view.View$PerformClick.run(View.java:19330)
05-22 00:58:02.083: E/MailApp(2890): at android.os.Handler.handleCallback(Handler.java:733)
05-22 00:58:02.083: E/MailApp(2890): at android.os.Handler.dispatchMessage(Handler.java:95)
05-22 00:58:02.083: E/MailApp(2890): at android.os.Looper.loop(Looper.java:157)
05-22 00:58:02.083: E/MailApp(2890): at android.app.ActivityThread.main(ActivityThread.java:5356)
05-22 00:58:02.083: E/MailApp(2890): at java.lang.reflect.Method.invokeNative(Native Method)
05-22 00:58:02.083: E/MailApp(2890): at java.lang.reflect.Method.invoke(Method.java:515)
05-22 00:58:02.083: E/MailApp(2890): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
05-22 00:58:02.083: E/MailApp(2890): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
05-22 00:58:02.083: E/MailApp(2890): at dalvik.system.NativeStart.main(Native Method)

rajesh.android said...

Maybe this cause by gmail account security protection, to disable
https://www.google.com/settings/security/lesssecureapps

Unknown said...

Hi all,

In this code we are stroing the password in our java file.

But here is a chance to steal the password by using de-compiler.

When we hardcode this email Id in our client code, if the end-user will be in different countries and our app will use the same email id to communicate. Due to this Gmail will force you to change the password due to account access from different IP address.

How to get ride of these security issue?
Please help me out on this?

rohit said...

android.os.NetworkOnMainThreadException

www.androidinterview.com

Unknown said...

For those of you getting the NetworkOnMainThreadException, you are getting this because the program is trying to send the email on the main UI of the program. This is not generally allowed by the OS, because imagine if that process failed, and blocked other network operations.

They way around this is to either use multithreading, i.e. implement Runnable(although I don't know much about this method), or an Async task

Unknown said...

How to attache a file
i got file not found exception