Sending Emails without User Intervention (no Intents) in Android

The Android SDK makes it very easy to send emails from an application, but unfortunately, that's only if you want to send them via the built-in mailing app. For most situations this works fine, but if you want to send something out and don't want any input/intervention from the user, it's not as easy.

In this article I'm going to show you how to send an email in the background without the user even knowing - the application will do everything behind the scenes.

Before we begin, you'll need to download a few files via the link below - this is a special version of the JavaMail API, which was written specifically for Android.

http://code.google.com/p/javamail-android/downloads/list

I'll be walking you through a Mail wrapper that I wrote, which makes it much easier to send emails and even add attachments if that's something you'd like to do.

Here is the full wrapper class below, which I'll go through step by step - keeping in mind that you'll have to add the fore-said files if you want this to work. Add them as external libraries - they need to be accessible by the Mail 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.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;


public class Mail 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 Mail() {
    _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 Mail(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 PasswordAuthentication getPasswordAuthentication() {
    return new 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;
  }

  // more of the getters and setters …..
}

And now I'm going to go through each bit of code


public Mail() {
  _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 Mail(String user, String pass) {
  this();

  _user = user;
  _pass = pass;
}

In this piece of code we initialise the properties, and setup the default values.

Also, we're setting up the mime types for javamail. I've also added a comment which describes why we need this.

And you've probably noticed that there are 2 constructors - one overrides the other, just incase the you want to pass the username and password when instantiating the class.


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;
  }
}

This is the most important method - here we're putting all the data from the properties and sending the mail.


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);
}

You can call this method at any time if you want to add an attachment, but make sure you call it before the send method.


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;
}

Here we're setting up the properties for the mail retrieval - defaulting to SMTP authentication.

Also keep in mind that this is all defaulted to connect to the Gmail (Google) SMTP server.

Below is an example of how to use the Mail wrapper, in an Android activity.


@Override
public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.main);

  Button addImage = (Button) findViewById(R.id.send_email);
  addImage.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
      Mail m = new Mail("gmailusername@gmail.com", "password");

      String[] toArr = {"bla@bla.com", "lala@lala.com"};
      m.setTo(toArr);
      m.setFrom("wooo@wooo.com");
      m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
      m.setBody("Email body.");

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

        if(m.send()) {
          Toast.makeText(MailApp.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
        } else {
          Toast.makeText(MailApp.this, "Email was not sent.", Toast.LENGTH_LONG).show();
        }
      } catch(Exception e) {
        //Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
        Log.e("MailApp", "Could not send email", e);
      }
    }
  });
}

jon | May 19, 2010 | Comments (95)

Comments

So I will have to embed my email name/password/server right into my code? Where anyone can read it, or sniff it out through the port?
Comment by Donna - January 29, 2012 @ 10:25 pm
getting the following error, please help and if possible mail me at mayurdhwajsinh@gmail.com

No enclosing instance of type MailApp is accessible. Must qualify the allocation with an enclosing instance of type MailApp (e.g. x.new A() where x is an instance of MailApp).
Comment by mayur - January 28, 2012 @ 6:09 am
Is it possible to RECEIVE the Gmail emails? I'm trying to create an app that will display gmail emails but can't find anywhere a way to grab them from the servers. Thanks
Comment by Phil Tucker - January 20, 2012 @ 7:32 pm
Hi,

I am getting javax.mail.AuthenticationFailedException error. I have rechecked username, password and all seem to be correct. Can someone please give hint to resolve the javax.mail.AuthenticationFailedException exception?

Thanks.

ps: I have got the source code of the jar files now. Thanks.
Comment by Ambi - January 15, 2012 @ 6:57 pm
Hi,

Thanks for the useful work.

Is the source code for the three jar files namely "additionnal.jar, mail.jar, activation.jar" available? If yes can you please provide the link?

Thanks,
Ambi.
Comment by Ambi - January 15, 2012 @ 2:04 pm
i got this error pleas help :

01-11 13:48:59.818: E/MailApp(29958): Could not send email
01-11 13:48:59.818: E/MailApp(29958): android.os.NetworkOnMainThreadException
01-11 13:48:59.818: E/MailApp(29958): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
01-11 13:48:59.818: E/MailApp(29958): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
01-11 13:48:59.818: E/MailApp(29958): at java.net.InetAddress.getLocalHost(InetAddress.java:371)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.InternetAddress.getLocalAddress(InternetAddress.java:517)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.UniqueValue.getUniqueMessageIDValue(UniqueValue.java:99)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.updateMessageID(MimeMessage.java:2054)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2076)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2042)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.Transport.send(Transport.java:117)
01-11 13:48:59.818: E/MailApp(29958): at com.fahadalawam.kwtresturant.Mail.send(Mail.java:125)
01-11 13:48:59.818: E/MailApp(29958): at com.fahadalawam.kwtresturant.Add$1.onClick(Add.java:58)
01-11 13:48:59.818: E/MailApp(29958): at android.view.View.performClick(View.java:3480)
01-11 13:48:59.818: E/MailApp(29958): at android.view.View$PerformClick.run(View.java:13983)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Handler.handleCallback(Handler.java:605)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Handler.dispatchMessage(Handler.java:92)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Looper.loop(Looper.java:137)
01-11 13:48:59.818: E/MailApp(29958): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-11 13:48:59.818: E/MailApp(29958): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 13:48:59.818: E/MailApp(29958): at java.lang.reflect.Method.invoke(Method.java:511)
01-11 13:48:59.818: E/MailApp(29958): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-11 13:48:59.818: E/MailApp(29958): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-11 13:48:59.818: E/MailApp(29958): at dalvik.system.NativeStart.main(Native Method)
Comment by fahad alawam - January 11, 2012 @ 10:53 am
To the author
I could not make this work for Microsoft Mail Exchange Server, any idea how to set up for Microsoft Exchange Server. thanks.
Comment by Mukunda - December 31, 2011 @ 10:17 am
Awesome!!! Worked like a charm!!!
Comment by Pravin - December 30, 2011 @ 6:47 am
hi can u please send me the zip file.. Thanks
Comment by senthil - December 27, 2011 @ 9:52 am
I m using emulator to test this, and getting the below error message "MailApp cannot be resolved to a type".

Also how does it recognizes the user's password. We are no where giving the password right? We are only giving From Email address.

Any help is much appreciated.
Comment by Ratnakar - December 25, 2011 @ 8:32 pm
Works perfectly. Thank you very much !
Comment by Bragaadeesh - December 24, 2011 @ 10:05 pm
I couldn't get this to working on Microsoft Email 365, any information would be helpful.
Tried with
Server name: podabc.outlook.com
Port: 587
Encryption method: TLS

but nothing worked.
thanks.
Comment by Mukunda - December 19, 2011 @ 1:21 pm
Hello,

Thank you for providing this information, so far your site is the only site that has answered my question!

I'm new at programming in java, and I cant seem to figure out how to 'load' this files into eclipse so I can get this to work. I know this is the answer, implementing it is whats giving me difficulty.

Can you create a quick video and post it on youtube so we can see how you did this?

Thanks alot
Comment by Justin - December 13, 2011 @ 7:21 pm
can u plz send the zip file of this code
Comment by poornima jr - December 10, 2011 @ 4:49 pm
Can you please send me this project's .zip file. I got lot of errors from this code.
Comment by Praveen Kumar - December 02, 2011 @ 10:16 am
hi,
Can you plz send the code in zip file on my email mail4satya@gmail.com. I am getting lots of errors in this.
Comment by Satya - November 30, 2011 @ 10:26 am
To author mr. Jon Simon.
Never helped anybody with knowhow. But im in shame today.
Cause I were forced to get Your help.
My project is saved!
Thank You,gentleman.
Comment by Huseynov Iskandar - November 26, 2011 @ 12:19 pm
To author mr. Jon Simon.
Never helped anybody with knowhow. But im in shame today.
Cause I were forced to get Your help.
My project is saved!
Thank You,gentleman.
SamGU.
Comment by Huseinov Iskandar - November 26, 2011 @ 12:10 pm
My application is used in locations with no network access, and the app should cache any outgoing messages until the network is available. Looks like this example does have that functionality - anyone know of an example that does?
Comment by Tom - November 18, 2011 @ 1:48 am
I also got this error, can anyone help me on this:
javax.mail.MesagingException: Unknown SMTP host: smtp.gmail.com; nested exception is:
java.net.UnknownHostException: Host is unresolved: smtp.gmail.com:465
Comment by karthik - November 08, 2011 @ 11:19 am
I try this code and it didn't work and they I realize it work only with gmail account that use one step verification.
and not the new 2-step verification.
if someone have an idea how to make it work with 2-step verification it will be great
Thanks for the code is really great
Comment by assaf passal - November 07, 2011 @ 3:25 pm
I get this error, can anyone help me on this:
javax.mail.MesagingException: Unknown SMTP host: smtp.gmail.com; nested exception is:
java.net.UnknownHostException: Host is unresolved: smtp.gmail.com:465
Comment by HT - October 20, 2011 @ 5:59 pm
" ... New to droid. Thank you for posting this tutorial. I am not getting any errors but I am getting "There was a problem sending the email.
..."
Hi Carl, you should check permission in the manifest file. Perhaps you forgot add permission for accessing internet
Comment by littleboy - October 10, 2011 @ 2:01 am
Works perfect for my project, thanks a lot!
Comment by IceCream - October 07, 2011 @ 7:33 pm
Hi..Thanks for this..It works very well if there are no attachments..But the moment I try to attach any file with the email, the app just stops responding..There is no error in logcat etc..but the email is never sent even for very small sized files and even after waiting a lot... Please help..
Comment by kusi - October 03, 2011 @ 5:51 am
This only works for SSL right. What about TLS?
Comment by gT - September 25, 2011 @ 5:30 am
Mail sending is working superb.
But do you know , how can we check whether the mail sent is successful or failed?
Comment by TechnoTalkative - September 23, 2011 @ 10:24 am
Hi, does it send the username and password to gmail encrypted? Where is this done?
Comment by andrew - September 19, 2011 @ 4:26 pm
Works great on Nexus S. Thanks.
Comment by KC - August 08, 2011 @ 2:56 pm
New to droid. Thank you for posting this tutorial. I am not getting any errors but I am getting "There was a problem sending the email." Any idea how to trace and fix?
Comment by carl - August 07, 2011 @ 2:38 am
hii this code is working fine with out attachment. when i am sending with attachment its send the file name is "noname" and inside file content is what ever i gave boby that one only inside file.
please help me send with attachment.
please send me the .zip file
my email is indela447@gmail.com
Comment by indela - July 29, 2011 @ 7:47 am
Thanks for the code.Working properly in all versions

But in Android1.6 It is forcefully closing the application.Any idea about this
Comment by Venkat - July 28, 2011 @ 11:15 pm
Hi! Thanks, got it to work with little effort, after a couple of the tweaks suggested, such as adding the permission to the Manifest file, and I also had to add a button to my own test main.xml named send_email.

Sending a regular e-mail without attachments works fine, but when I try to attach a jpg that is in my res/drawable folder, it errors out on the line:

// send email
Transport.send(msg);

The addAttachment code seemed to handle my filepath OK, but I don't know if my filepath is valid. Do you know what the absolute path is for a jpg in the res/drawable folder? I was trying this code:


String filepath = Uri.parse("android.resource://com.michaeljdougan.mikemail/" + R.drawable.e002_c).toString();
m.addAttachment(filepath);

And filepath looks like:
"android.resource://com.michaeljdougan.mikemail/20137496"

I've used similar code to attach a jpg using code for the built-in e-mail program, in a putExtra(EXTRA_STREAM statement, and it worked.

Do you know if you have to copy the attachments to the SD card before attaching to an email? I'm testing using the simulator, and there is no SD card in the simulator.

For those that say you can't do this with the simulator, it does send the e-mail fine, without an attachment, and I can even send an attachment using the built-in email program, as long as I've setup my e-mail client properties (smtp server etc).

Thanks in advance!
Comment by Mike - July 27, 2011 @ 11:12 pm
Just remember there is an Open Source project for SMS Backup that uses a Gmail account to store and retrieve SMS messages. There should be enough information on both sending and receiving email messages. http://code.google.com/p/android-sms/

You need to use subversion to pull a copy of the source code. svn checkout http://android-sms.googlecode.com/svn/trunk/ android-sms-read-only
Comment by Ernie - July 13, 2011 @ 7:50 pm
When I called the send() method, I am getting a java.io.IOException. Couldn't connect using "javax.net.sll.SLLSocketFactory" ClassNotFoundException: javax.net.sll.SSLSocketFactory.

Shouldn't it be javeax.net.ssl.SSLSocketFactory??

Do I need to go to the JAR files to correct this? TIA.
Comment by Ernie - July 13, 2011 @ 7:34 pm
It took me a while to figure out all the errors I was getting, but I must say, reading through all the comments really helps as well.

Thanks for this post, really awesome.

For future reference, is there no way of adding the missing code back into the main post to save other people the trouble?
Comment by Evan - July 12, 2011 @ 8:58 am
Excellent work!

lol @ the users asking you to contact them personally via email with a solution to their problem
Comment by PodeCoet - July 08, 2011 @ 2:02 am
zohaibbrohi@gmail.com .. thats my id Thanks
Comment by Zohaib - July 07, 2011 @ 1:34 am
Please mail me zip file of this program. thanks
Comment by Zohaib - July 07, 2011 @ 1:33 am
Hi,

perfect tutorial, works very well! Thanks alot for that!

But: I tried to add a bcc recipient, which doesnt work. Instead, a copy to the _to recipient is send twice. I used a similiar code as for adding recipients in mail.java.

Do you know a solution?
Comment by javadev - June 09, 2011 @ 1:17 pm
thanks a lot man its really working...you've solve my problem thank you very much...
Comment by Nikunj Dhamat - May 30, 2011 @ 11:26 am
How do I set the mime type for an attachment?? I need to be able to set it to a custom mime type so that when I get the email on another phone I can launch my app from the attachment.

Thanks very much for this code!!
Comment by David Pfeiffer - May 27, 2011 @ 2:51 am
Hi Rick,
I think that it doesn't suppose to work on an emulator, only on a real device.
Try checking it on your phone.

Good luck, Elad
Comment by Elad - May 18, 2011 @ 1:29 pm
Hi Elad

I was wondering are you trying this from an actual phone or are you using the emulator?
Comment by Rick - May 18, 2011 @ 1:24 pm
Great, works for me!
But isn't it bit risky to put your password? someone can easily decompile the apk.. Any suggestions?
Thanks
Comment by Elad - May 18, 2011 @ 9:07 am
I get the following exception when running this on the emulator - javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; java.net.SocketException: Permission denied. Any one run into this one?

Comment by Rick - May 16, 2011 @ 5:44 pm
Hello, I tried to compile the code and I get the following errors .. please help me to solve them. Thanks in advance.

23:18:00.703 904 ERROR dalvikvm Could not find class 'org.me.emailtestandroid.Mail', referenced from method org.me.emailtestandroid.MainActivity$1.onClick
23:18:11.974 904 ERROR AndroidRuntime FATAL EXCEPTION: main
23:18:11.974 904 ERROR AndroidRuntime at org.me.emailtestandroid.MainActivity$1.onClick(MainActivity.java:33)
23:18:11.974 904 ERROR AndroidRuntime at android.view.View.performClick(View.java:2485)
23:18:11.974 904 ERROR AndroidRuntime at android.view.View$PerformClick.run(View.java:9080)
23:18:11.974 904 ERROR AndroidRuntime at android.os.Handler.handleCallback(Handler.java:587)
23:18:11.974 904 ERROR AndroidRuntime at android.os.Handler.dispatchMessage(Handler.java:92)
23:18:11.974 904 ERROR AndroidRuntime at android.os.Looper.loop(Looper.java:123)
23:18:11.974 904 ERROR AndroidRuntime at android.app.ActivityThread.main(ActivityThread.java:3683)
23:18:11.974 904 ERROR AndroidRuntime at java.lang.reflect.Method.invokeNative(Native Method)
23:18:11.974 904 ERROR AndroidRuntime at java.lang.reflect.Method.invoke(Method.java:507)
23:18:11.974 904 ERROR AndroidRuntime at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
23:18:11.974 904 ERROR AndroidRuntime at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
23:18:11.974 904 ERROR AndroidRuntime at dalvik.system.NativeStart.main(Native Method)
Comment by Luca - May 07, 2011 @ 11:38 pm
Works like a charm !!

Thanks alot!!
Comment by Shrey Malhotra - May 07, 2011 @ 12:27 pm
well i am new to android . i had tried this code but it does not work . So can i have the source code of this.
Comment by Ratnesh - May 05, 2011 @ 10:20 am
I'll try and find my project file and post the link in the next couple of days - sorry for the delayed response...
Comment by Jon - April 25, 2011 @ 7:57 pm
I m facing red cross where is written MailApp. what is this and wats the solution. plz help me. If possible, anyone send me zipped file on goforseeking@yahoo.com

Thanx
Comment by Muhammad Asif - April 22, 2011 @ 2:41 pm
Thanks it works, it didn't at first because the emulator was stack or something. But it worked after I restarted the emulator.
thx
Comment by NewAndMan - April 17, 2011 @ 2:17 pm
"java.lang.NoClassDefFoundError" Solved.

The problem is Eclipse screw up for reference jar. After change .classpath .. able to send mail already..
Comment by kyaw - April 13, 2011 @ 1:37 am
Its not complain when I compile at eclipse, But In runtime i got this error..
java.lang.NoClassDefFoundError

how do I solve ?
Comment by kyaw - April 12, 2011 @ 7:33 am
hey guys the information here is very useful..but somehow i was not able to make it run..but finally i m able to successfully send mail on click of button..thanks dude..but this guy seems bit busy..let me do it for u ..mail me whoever want the complete running code
..praveenkanade@yahoo.com
Comment by praveen - April 12, 2011 @ 1:11 am
Thank you for all the usefull information. Can you send me the zip file for your eclipse project, it will help me understand this alot. Thanks
Comment by Brandon - April 12, 2011 @ 12:49 am
hiii ,
i am trying to do this ,but there is nothing showing (the project is running well,there is no error)..i have done every thing ,like completed uses-permission,and have write extra methods(setFrom,setSubject etc)...but my project is not showing anything ...its only showing a button and also its not showing the Toast materials...please someone help me...its very important for me.

advance thanks,
Manoj
Comment by Manoj Behera - April 06, 2011 @ 9:42 am
thanks
Comment by raju - April 01, 2011 @ 9:54 am
Because of this line:
Mail m = new Mail("myusername@gmail.com", "mypassword");

I get this error any ideas :
jar:
Result: -1
pkg: /data/local/tmp/AutomatedEmail.apk
Success
33 KB/s (6951 bytes in 0.204s)
About to start org.me.automatedemail/org.me.automatedemail.AutoEmail
DDM dispatch reg wait timeout
Can't dispatch DDM chunk 52454151: no handler defined
Can't dispatch DDM chunk 48454c4f: no handler defined
Starting: Intent { cmp=org.me.automatedemail/.AutoEmail }
run:
BUILD SUCCESSFUL (total time: 48 seconds)
Comment by Newbie - March 30, 2011 @ 2:18 am
Please send me the .zip file..
thank u.......
Comment by praveen - March 28, 2011 @ 11:56 am
excellent tutorial.
worked in the first go.
Comment by saurabh - March 23, 2011 @ 10:07 pm
wowww..
can send me the zip project file??
thankss.
Comment by basit - March 22, 2011 @ 3:13 am
can u send me .zip file.
thanks in advance!!!!!
Comment by nis - March 12, 2011 @ 8:06 pm
can same code work for yahoo or hotmail also??
Comment by sneha - March 10, 2011 @ 10:24 am
Worked for me - thanks!
Comment by Raj - March 06, 2011 @ 6:46 pm
Getting exception javax.mail.AuthenticationFailedException..

please help

thanks in advance
Comment by chaitanya - March 04, 2011 @ 11:21 am
worked for me, after setting the internet permission on. Thank you.
Comment by prashant sharma - February 28, 2011 @ 11:50 am
Can you please send me your project in .zip for eclipse because i am getting quite a few errors and it would help me out a lot if the .zip file were in front of mr
Comment by Ronil - February 25, 2011 @ 10:52 am
this code is not working for hotmail and yahoo. how this possible?
Comment by kamran - February 23, 2011 @ 10:22 am
Thanks a lot, that was awesome :D. Exactly what i needed
Comment by MrMaffen - February 17, 2011 @ 6:15 pm
Could not connect to SMTP host: mail.geosafetynet.com, port: 25


Any Ideas? I want to use my own mail server. Please contact back via email.
Comment by Walter - January 28, 2011 @ 12:08 am
I could not run the code.
It giving me SMTP Exception.

Can you please send the code my Email.
Thank you
Comment by Jeevan - January 26, 2011 @ 10:04 pm
Can you please send me your project in .zip for eclipse? I'm getting errors while trying to send an email (cannot connect to SMTP host). Thanks!
Comment by ViewSonic - January 20, 2011 @ 10:59 pm
Thanks its working now!!
Good Work!!
Comment by Deepanshu - January 19, 2011 @ 8:49 am
hi,
Can you plz send the code in zip file on my email deepanshu.wad@gmail.com.
Bcz i am getting errors in this.
I am in urgent need plz help!!
Comment by Deepanshu - January 19, 2011 @ 5:55 am
Hi, can you maybe provide an export of an whole eclipse android project so i can have a look at it and get an impression of how to implement htis whole thing.

Thank you;)
Comment by Spazzt - January 17, 2011 @ 6:22 pm
Very useful code - thanks!

Is there any way to avoid having to specify the sending password, maybe by using AccountManager to authenticate with the phone's gmail account?
Comment by Craig - January 06, 2011 @ 1:24 am
hey please tell me how to give the path of internal storage to send a file
Comment by rakshith - January 05, 2011 @ 5:22 am
As stated above, your SMTP example works perfected. This has been a great help. I also see that (according to http://code.google.com/p/javamail-android/) you also have imap working and tested. Do you have any sample code for your imap feature.
Again may thanks.
Comment by Max Jackson - January 04, 2011 @ 8:11 pm
Fantastic stuff. Thanks for taking the time to post this.
Comment by owen - January 02, 2011 @ 2:48 am
hey please help, the mail not delivered
Comment by rakshith - December 28, 2010 @ 5:02 pm
Awesome, thank you! This works perfectly!
Comment by mo - December 21, 2010 @ 9:57 pm
please send totla source.zip file
Comment by kiran - December 17, 2010 @ 6:52 am
Thank you so much!!!
*hug*

I first ran into a "Untrusted Certificate" issue (due to my self signed cert) that I had to resolve by adding this to my code

static {
Security.addProvider(new JSSEProviderHarmony());
}

with:

public final class JSSEProviderHarmony extends Provider {

public JSSEProviderHarmony() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");

AccessController.doPrivileged(new java.security.PrivilegedAction() {
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;
}
});
}
}

and had to add a "TrustAllSSLFactory" by
replacing

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

with

props.setProperty("mail.smtp.socketFactory.class", "com.ur.app.TrustAllSSLSocketFactory");

at ur method setProperties().


public class TrustAllSSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory factory;

public TrustAllSSLSocketFactory() {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null,
new TrustManager[] { new TrustAllTrustManager()},
null);

factory = (SSLSocketFactory)sslcontext.getSocketFactory();
} catch(Exception ex) {
// ignore
}
}


public static SocketFactory getDefault() {
return new TrustAllSSLSocketFactory();
}

@Override
public Socket createSocket(Socket socket, String s, int i, boolean flag)
throws IOException {
return factory.createSocket(socket, s, i, flag);
}

@Override
public Socket createSocket(InetAddress inaddr, int i,
InetAddress inaddr1, int j) throws IOException {
return factory.createSocket(inaddr, i, inaddr1, j);
}

@Override
public Socket createSocket(InetAddress inaddr, int i)
throws IOException {
return factory.createSocket(inaddr, i);
}

@Override
public Socket createSocket(String s, int i, InetAddress inaddr, int j)
throws IOException {
return factory.createSocket(s, i, inaddr, j);
}

@Override
public Socket createSocket(String s, int i) throws IOException {
return factory.createSocket(s, i);
}

@Override
public Socket createSocket( ) throws IOException {
//log.debug( "createSocket 0");
return factory.createSocket();
}

@Override
public String[] getDefaultCipherSuites() {
return factory.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}
}


On the server side the default postfix master.cf file has to have enabled smtps with
smtpd_tls_wrappermode=yes
smtpd_sasl_auth_enable=yes

to prevent:
java.io.IOException: SSL handshake failure: Failure in SSL library, usually a protocol error

error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:604 0xaf076228:0x00000000)
Comment by happydude - December 06, 2010 @ 11:40 pm
Great stuff! Tested it a few minutes ago, and it does work, even with attachments!
Comment by Finkle - November 28, 2010 @ 7:05 pm
I have used attachment part from the above code, I am able to send email with attachment but my email body is also send as attachment.

Can anyone hele me regarding the same.
Comment by ravi - November 22, 2010 @ 5:07 am
Hi,I'm Chinese.new to java,new to android,completely new to javamail.I'm trying to code an apk to mail Message on android phone to email account,your artical helps very much,the only one that workde this days,thank you very much!
Comment by songshijia88888 - November 06, 2010 @ 10:35 pm
Oops, it didn't take. The XML tag is (left bracket) uses-permission android:name="android.permission.INTERNET" /(right bracket).
Comment by SteV-O - October 29, 2010 @ 5:45 am
Hello, thanks for posting this! It works like a dream.

I must suggest one thing to anyone having trouble getting this to work: you must add the XML tag to your AndroidManifest.xml file. It took me several hours to figure this out. Also took before I realized that to set this in Eclipse, don't just type INTERNET; type android.permission.INTERNET. (Also once I got it working, the message I sent landed in Spam.)
Comment by SteV-O - October 29, 2010 @ 5:43 am
This was incredibly useful and works perfectly for me. Thanks!

@Reza Nezami

You can make this send HTML content by replacing this bit of the 'send()' method:

// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);

with

// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(_body, "text/html");
_multipart.addBodyPart(messageBodyPart);


You could obviously make the mime type here a parameter that you pass into setBody().
Comment by zonski - September 29, 2010 @ 1:21 am
I've been trying to make this class work, but i got this error:


09-28 15:42:26.382: ERROR/MailApp(4363): javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
09-28 15:42:26.382: ERROR/MailApp(4363): nested exception is:
09-28 15:42:26.382: ERROR/MailApp(4363): java.io.IOException: SSL handshake failure: Failure in SSL library, usually a protocol error
09-28 15:42:26.382: ERROR/MailApp(4363): error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:585 0xaf589f78:0x00000000)

Any help please?
Comment by Oscar Davila - September 28, 2010 @ 8:42 pm
Wandering if it's possible to send html content (not attachment) like this? sending plain text works fine.
thx
Comment by Reza Nezami - September 24, 2010 @ 3:06 am
PLEASE NOTE: The example code (wrapper) above is missing a couple of required setters. You will need to add them yourself:


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

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

public void setSubject(String string) {
this._subject = string;
}
Comment by Matt Farley - September 17, 2010 @ 5:13 pm
Just wanted to say I spent hours searching the web and your solution was the only one I found that worked!

Thank you!
Comment by Matt Farley - September 17, 2010 @ 5:00 pm
Can this be done on the iphone???
Comment by mark - July 17, 2010 @ 9:25 pm

Name (required)
Email (will not be published) (required)
Website

captcha