Need help?

I'm available for remote short term contracting or consultancy work. Please check out my LinkedIn profile for more details on my experience.

Please feel free to use the form below to contact me.




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 (158)

Comments

The other day, while I was at work, my cousin stole my iphone and tested to see if it can survive a
25 foot drop, just so she can be a youtube sensation.
My apple ipad is now destroyed and she has 83 views.
I know this is totally off topic but I had to share it with someone!
Comment by Blair - October 18, 2012 @ 11:18 pm
Please let me know if you're looking for a article writer for your site. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I'd really like to write some content for your blog
in exchange for a link back to mine. Please blast me an
e-mail if interested. Kudos!
Comment by Reginald - October 18, 2012 @ 8:40 pm
It's in reality a nice and helpful piece of information. I'm happy
that you shared this useful info with us. Please stay us up to date like this.
Thanks for sharing.
Comment by Millie - October 17, 2012 @ 8:42 pm
My brother recommended I would possibly like this web site.
He was entirely right. This submit truly made my day.
You can not consider just how much time I had spent for this info!
Thanks!
Comment by Tania - October 14, 2012 @ 9:35 pm
Spot on with this write-up, I absolutely feel this web site needs
a lot more attention. I'll probably be returning to read more, thanks for the information!
Comment by Ron - October 14, 2012 @ 4:44 am
I may be shopping to loose weight for so very long. After reading
this I really think I am going to be wanted to have a go because I have just about given up hope.
I saw that Dr Oz remarked about some products including 7keto
and kinda hope this functions at the same time.
Comment by Victorina - October 14, 2012 @ 1:40 am
Greetings! Very useful advice in this particular article!
It's the little changes that produce the most significant changes. Thanks a lot for sharing!
Comment by Kandace - October 13, 2012 @ 5:12 am
I used to be recommended this web site via my cousin.
I am no longer positive whether this publish is written by way of him as nobody else recognise such designated about my trouble.
You are wonderful! Thanks!
Comment by Gene - October 12, 2012 @ 8:46 pm
I'm not certain where you're getting your info, but good topic.
I needs to spend some time learning more or understanding more.

Thank you for fantastic info I was searching for this information for my
mission.
Comment by Foster - October 12, 2012 @ 7:29 pm
I am really loving the theme/design of your site.
Do you ever run into any internet browser compatibility problems?

A number of my blog readers have complained about my blog not operating correctly in
Explorer but looks great in Chrome. Do you have any tips to help fix this problem?
Comment by Sophia - October 12, 2012 @ 5:42 pm
I tremendously want to steer trucks like I utilise exceedingly.
As a result of the later years atmosphere it their staying an increasingly to completely enable it to be inside
and out of each of the play vehicles. I remember back when I must
have been a younger kid and might revolve
appreciate the fulfilling ticket processing through my lead several I required accomplish is
film down the window. But this was in that case your is currently, I am just an older
man over the age of 70 there is certainly my legs beginning to hand out its high less excitement pushing an automatic automobile given that it
were enjoy a stunning hands-on 1. I are Aware Of technology presently has gotten beyond control and
really beginning increase making it to certainly man that could change anywhere close to as quickly
as a a woman who commuting a complete computerized bringing adjust.
I understand that in formal one and mascara utilize
automatics finally.
I americium not to imply it's just not entertaining, however its vigorously to release enjoyable tension there is by driving on the extremity and getting the velocity extract an individual your support. Or during the time you would hit a turn and possess those 3g turns and choose stuck high while endeavoring to change your assailant. Oh home buying when I used to race, I identify I can certainly still perform a many things therefore effective rejoice pertains well offer.
When I was young we didn't suitable stuff men accomplish nowadays and while you can smash this offend very it would be easiest keen to accept.
This create consumers wondering why they were racing.
Actually it was subsequently safer to make for many people or
should aim to haul activities than it has been into fly.

Racing have not actually been a considerable expenses vendor now for
the runners till now.
A single solution which controlled me as I show arrived aged is my effect
time is not near what it was formerly. For some reason does make
a person not need test and do lots of things after having
that occur nevertheless its something you observe medicine running roughly in great vehicles and dreaming about individuals to look.

Maybe someday I can start paying some games, I found a few sites that where cool
that can be played some auto racing sports however it would not everything I
decided it would. Quite I need for an Xbox or even a Manufacturers and try
their sport games; I wont understand s not an equivalent pressuring buttons in lieu of noticing it
hit you all through face.
But what you going to do? You should only live when and might besides get the most from it simply be secure though I will tell you that there's rarely far too much protective particularly if we are going fine over hundred cientos per day or perhaps in 60 minutes.
Comment by Delila - October 12, 2012 @ 4:16 am
You ought understand appreciate you doing every one of the analysis to build this.
It's a matter I most likely to be actively looking to get more motivated in investigating, meaning that your post helps me a decent amount!
Comment by Steve - October 11, 2012 @ 10:35 pm
Have you ever considered creating an e-book or guest authoring on other
websites? I have a blog centered on the same subjects you discuss and would really like to
have you share some stories/information. I know my subscribers
would appreciate your work. If you're even remotely interested, feel free to shoot me an e-mail.
Comment by Debbie - October 10, 2012 @ 5:16 am
hey there and thank you for your info – I have definitely picked up something new from right
here. I did however expertise a few technical issues using this web
site, since I experienced to reload the web
site a lot of times previous to I could get it to load correctly.
I had been wondering if your web hosting is OK?
Not that I am complaining, but sluggish loading
instances times will often affect your placement in google and could damage your quality score if advertising and marketing with Adwords.
Well I'm adding this RSS to my e-mail and could look out for a lot more of your respective exciting content. Make sure you update this again soon.
Comment by Roseann - October 08, 2012 @ 7:25 am
Wow, awesome weblog structure! How lengthy have you ever been running a blog for?
you make running a blog look easy. The overall look of
your site is wonderful, let alone the content!
Comment by Dan - October 08, 2012 @ 5:34 am
Amazing! This blog looks exactly like my old one! It's on a completely different topic but it has pretty much the same layout and design. Outstanding choice of colors!
Comment by Drew - October 07, 2012 @ 9:05 pm
excellent blog I'm a big United supporter from Sweden
Comment by Jens - October 07, 2012 @ 10:12 am
My brother recommended I may like this web site. He used to be entirely right.
This post actually made my day. You cann't believe just how much time I had spent for this info! Thank you!
Comment by Zelda - October 06, 2012 @ 5:25 pm
There's certainly a great deal to learn about this issue. I like all the points you have made.
Comment by Elvis - October 06, 2012 @ 4:16 am
I simply could not go away your website prior to suggesting that I really enjoyed
the usual info a person provide on your visitors? Is gonna be back regularly in order to inspect new posts
Comment by Pedro - October 05, 2012 @ 5:25 pm
I am regular reader, how are you everybody? This article posted
at this website is genuinely nice.
Comment by Betsy - October 04, 2012 @ 5:54 pm
I simply retweeted this Sending Emails without User Intervention (no Intents) in Android.
Comment by Stacy - October 04, 2012 @ 5:27 pm
I can simply tell who is good from the average. Congratulations for coming up
with this blog. Standing ovation!
Comment by Rod - October 04, 2012 @ 4:32 pm
These are genuinely fantastic ideas in regarding blogging.

You have touched some fastidious things here. Any way keep up wrinting.
Comment by Lawerence - October 04, 2012 @ 12:52 pm
Hi there, after reading this amazing piece of writing i am
as well glad to share my familiarity here
with friends.
Comment by Myrna - October 03, 2012 @ 5:44 pm
Hello There. I found your blog using msn. This is a very well written article.
I’ll be sure to bookmark it and come back to read more
of your useful info. Thanks for the post. I’ll
definitely return.
Comment by Freya - October 03, 2012 @ 9:04 am
Thanks a lot for sharing this with all people you really recognize what you're talking approximately! Bookmarked. Kindly also talk over with my web site =). We can have a link change arrangement among us
Comment by Terry - October 03, 2012 @ 7:31 am
Have you ever considered writing an e-book or guest authoring on other websites?
I have a blog based on the same topics you discuss and would love to have you share
some stories/information. I know my audience would appreciate your work.
If you are even remotely interested, feel free to shoot me an email.
Comment by Lindsey - October 02, 2012 @ 4:23 am
I'm having problem on my click event this part:
m.setTo(toArr);
m.setFrom("wooo@wooo.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
please help
Comment by japZ - September 03, 2012 @ 9:14 pm
Hey there, You've done an excellent job. I will definitely digg it and personally recommend to my friends. I am sure they'll be benefited from this website.
Comment by Nolan - September 03, 2012 @ 3:29 pm
Hey I got the same error like "Comment by fahad alawam - January 11, 2012 @ 5:53 am".

What does this exception "NetworkOnMainThreadException" mean?

Thank you for publishing this code.

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 Thomas - September 02, 2012 @ 7:34 pm
Your style is unique in comparison to other people I've read stuff from. Thank you for posting when you've got
the opportunity, Guess I'll just book mark this web site.
Comment by Vickie - August 31, 2012 @ 8:00 am
I drop a leave a response whenever I appreciate a article on a site or
I have something to contribute to the conversation.
Usually it is a result of the fire displayed in the article I browsed.
And on this article Sending Emails without User Intervention (no Intents) in Android. I was excited enough to drop a thought ;-) I do have a couple of questions for you
if it's okay. Could it be simply me or does it appear like some of these remarks come across like written by brain dead visitors? :-P And, if you are posting on additional online sites, I'd
like to keep up with you. Could you list the complete urls of all your public
pages like your linkedin profile, Facebook page or twitter feed?
Comment by Wilfredo - August 27, 2012 @ 2:30 pm
First off I would like to say excellent blog! I had a quick question that I'd like to ask if you don't mind.
I was interested to know how you center yourself and clear your head
prior to writing. I've had a hard time clearing my thoughts in getting my ideas out there. I truly do take pleasure in writing but it just seems like the first 10 to 15 minutes are wasted simply just trying to figure out how to begin. Any recommendations or hints? Kudos!
Comment by Jude - August 26, 2012 @ 6:37 pm
An outstanding share! I have just forwarded this onto a coworker who had been conducting a little
homework on this. And he in fact ordered me breakfast because I stumbled upon it for him.
.. lol. So allow me to reword this.... Thanks for the meal!
! But yeah, thanx for spending some time to talk about this subject
here on your web page.
Comment by Jorge - August 26, 2012 @ 11:38 am
Pretty nice post. I just stumbled upon your blog and
wanted to say that I've really enjoyed surfing around your blog posts. In any case I will be subscribing to your rss feed and I hope you write again very soon!
Comment by Alejandro - August 25, 2012 @ 2:17 pm
Cannot wait to take off in between the forest (blank).
Comment by Agnes - August 17, 2012 @ 2:58 pm
can u plz send the zip.file of the project
Comment by rebai - August 16, 2012 @ 3:12 pm
This code is excellent! Works perfectly for sending mail in the background. I have one question: when the email is being sent does it pause/freeze your app while sending mail? I'm wondering because I want to put a progress dialog for when mail is being sent but the progress spinner won't move. It doesn't even appear unless I sleep the thread. Any help would be greatly appreciated.
Comment by Jordan - August 15, 2012 @ 10:13 am
Have you ever thought about adding a little bit more than just your articles?
I mean, what you say is fundamental and everything. However imagine if you added some great
visuals or video clips to give your posts more, "pop"!

Your content is excellent but with pics and video
clips, this blog could certainly be one of
the most beneficial in its niche. Amazing blog!
Comment by Emanuel - August 13, 2012 @ 9:08 pm
OK now it works folks, yes even on the latest android versions :)

So here is the deal: for SDK 9 and later, you have to put the code in a different thread than the UI thread. You can, for example, handle the code in an AsyncTask.

Another rude way to overcome the problem is to add the following code before using the Mail. But I truly don't recommend it.

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Your code has worked fine for me including attachments to the email. The only small problem I see is that the name of the attachments are based on the source file full pathname which is certainly too long. The file name would have been sufficient I think. Going to see if I can fix that in the source code provided...

Still, it is a great shoot. You have my thanks for this.
Comment by Alain - August 10, 2012 @ 6:09 am
I have experienced exactly the same problem as
fahad alawam - January 11, 2012 @ 5:53 am. The android version concerned is 4.0.3 (SDK level 15).

This is a good piece of code. So is there a way to fix the problem? Some device settings to make in order to have the feature operate? A solution requiring android permissions of system level is fine with me.
Comment by Alain - August 10, 2012 @ 5:39 am
My developer is trying to persuade me to move to .

net from PHP. I have always disliked the idea because of the costs.
But he's tryiong none the less. I've been using WordPress on
a number of websites for about a year and am nervous about switching to another platform.
I have heard good things about blogengine.net. Is there a way I can transfer
all my wordpress content into it? Any kind of help
would be really appreciated!
Comment by Beatriz - August 09, 2012 @ 8:58 am
I have read so many posts concerning the blogger lovers however
this post is actually a good piece of writing, keep
it up. Check out my website to get more info about car insurance in California, if you like.
Comment by Kristian - August 04, 2012 @ 7:52 am
Please let me know if you're looking for a article author for your weblog. You have some really good articles and I think I would be a good asset. If you ever want to take some of the load off, I'd absolutely love to write some
articles for your blog in exchange for a link back to mine.
Please send me an email if interested. Kudos!
Comment by Branden - July 24, 2012 @ 10:11 am
Great.

But the SDK level must be smaller than 9.

If not, the app will crashed because we are not allowed to do this...
Comment by Felix Group - July 20, 2012 @ 11:04 am
Great.

But the SDK level must be
Comment by Felix Group - July 20, 2012 @ 11:03 am
Howdy! Would you mind if I share your blog with my zynga group?
There's a lot of folks that I think would really enjoy your content. Please let me know. Many thanks
Comment by Tatiana - July 19, 2012 @ 7:55 am
Well Done - Thanks for such an awesome class! For exchange users, your ssl port is 993.

More exchange port info here: http://support.microsoft.com/kb/278339.

If you are having any connection issues ("Could not connect to SMTP host: xyz.mail.com Port: 25") - start your debugging process by commenting out the lines below in the _setProperties() function to disable the ssl negotiation.

//DISABLE SSL CONNECTION
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "true");


Also, make sure the value below is set to, "true"
props.put("mail.smtp.socketFactory.fallback", "true");

Cheers!

Comment by Rob Catalano - July 16, 2012 @ 12:54 pm
Hi! This post couldn't be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this write-up to him. Fairly certain he will have a good read. Thanks for sharing!
Comment by Chara - July 16, 2012 @ 3:03 am
Thanks on your marvelous posting! I actually enjoyed
reading it, you could be a great author. I
will make sure to bookmark your blog and will eventually come back in the foreseeable future.
I want to encourage that you continue your great posts, have a nice weekend!
Comment by Galen - July 03, 2012 @ 12:27 am
Is this code will work in Android Emulator???

or Can you send me the zip file of your code??
Comment by AndroidMail - June 24, 2012 @ 3:44 pm
Aw, this was a really nice post. Spending some time and
actual effort to produce a really good article… but what can I say… I put things off a lot and don't seem to get anything done.
Comment by Genesis - June 22, 2012 @ 7:48 pm
Thanks
Comment by Robson - June 13, 2012 @ 10:01 am
Thanks a lot.

But if i want to use my own domain instead of gmail, what should i do?

Thanks again for the guideline.
Comment by Hasan - June 11, 2012 @ 7:42 am
thank u so much... this help me lot...
really helpful..
:)
Comment by Amol Sawant - June 06, 2012 @ 1:17 am
Hi author, can u send me the complete source code in zip. Thank you very much.
Comment by Jasvin - June 03, 2012 @ 12:39 pm
work like a charm!! muaaahhh 10x a lot!!! keep it up!!
Comment by arya - May 11, 2012 @ 6:24 am
Perfect!
Comment by Igor - April 18, 2012 @ 12:44 pm
For those having the java.lang.NoClassDefFoundError issue:

1. Make sure you add the items as JARs rather than External JARs. You do this by clicking the project, then selecting "Build Path", then selecting "Configure Build Path".

2. Make sure you check the box next to the JARs you just added. This is done under the "Order and Export" tab.

Also, make sure you add the following permission to your manifest file:


Comment by Auri Rahimzadeh - April 17, 2012 @ 3:04 pm
I am getting the following error:

Unsupported action - That action is not currently supported

Please let me know how to solve it.
Comment by James - April 13, 2012 @ 5:34 am
First of all thank you for this article.
Here is my question : How can I receive mail with JavaMail Api or another Api on Android Project. I have been trying for this, but I couldnt find any working code on Android Application. I hope you can give me an idea about this situation.
Comment by Merve - March 22, 2012 @ 1:49 pm
Hi Jon,

This is a great howto, the code is very easy to follow & understand! Thanks very much for posting it!
Comment by Andrew - February 13, 2012 @ 10:48 pm
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 @ 5: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 @ 1: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 @ 2: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 @ 1: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 @ 9:04 am
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 @ 5: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 @ 5:17 am
Awesome!!! Worked like a charm!!!
Comment by Pravin - December 30, 2011 @ 1:47 am
hi can u please send me the zip file.. Thanks
Comment by senthil - December 27, 2011 @ 4: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 @ 3:32 pm
Works perfectly. Thank you very much !
Comment by Bragaadeesh - December 24, 2011 @ 5: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 @ 8:21 am
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 @ 2:21 pm
can u plz send the zip file of this code
Comment by poornima jr - December 10, 2011 @ 11:49 am
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 @ 5: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 @ 5: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 @ 7:19 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.
SamGU.
Comment by Huseinov Iskandar - November 26, 2011 @ 7:10 am
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 17, 2011 @ 8:48 pm
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 @ 6: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 @ 10:25 am
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 @ 1: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 09, 2011 @ 10:01 pm
Works perfect for my project, thanks a lot!
Comment by IceCream - October 07, 2011 @ 3: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 @ 1:51 am
This only works for SSL right. What about TLS?
Comment by gT - September 25, 2011 @ 1: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 @ 6:24 am
Hi, does it send the username and password to gmail encrypted? Where is this done?
Comment by andrew - September 19, 2011 @ 12:26 pm
Works great on Nexus S. Thanks.
Comment by KC - August 08, 2011 @ 10:56 am
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 06, 2011 @ 10:38 pm
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 @ 3: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 @ 7: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 @ 7: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 @ 3: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 @ 3: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 @ 4: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 07, 2011 @ 10:02 pm
zohaibbrohi@gmail.com .. thats my id Thanks
Comment by Zohaib - July 06, 2011 @ 9:34 pm
Please mail me zip file of this program. thanks
Comment by Zohaib - July 06, 2011 @ 9:33 pm
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 @ 9:17 am
thanks a lot man its really working...you've solve my problem thank you very much...
Comment by Nikunj Dhamat - May 30, 2011 @ 7: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 26, 2011 @ 10:51 pm
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 @ 9:29 am
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 @ 9:24 am
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 @ 5: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 @ 1: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 @ 7:38 pm
Works like a charm !!

Thanks alot!!
Comment by Shrey Malhotra - May 07, 2011 @ 8:27 am
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 @ 6: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 @ 3: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 @ 10:41 am
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 @ 10:17 am
"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 12, 2011 @ 9:37 pm
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 @ 3: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 11, 2011 @ 9:11 pm
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 11, 2011 @ 8:49 pm
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 @ 5:42 am
thanks
Comment by raju - April 01, 2011 @ 5: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 29, 2011 @ 10:18 pm
Please send me the .zip file..
thank u.......
Comment by praveen - March 28, 2011 @ 7:56 am
excellent tutorial.
worked in the first go.
Comment by saurabh - March 23, 2011 @ 6:07 pm
wowww..
can send me the zip project file??
thankss.
Comment by basit - March 21, 2011 @ 11:13 pm
can u send me .zip file.
thanks in advance!!!!!
Comment by nis - March 12, 2011 @ 3:06 pm
can same code work for yahoo or hotmail also??
Comment by sneha - March 10, 2011 @ 5:24 am
Worked for me - thanks!
Comment by Raj - March 06, 2011 @ 1:46 pm
Getting exception javax.mail.AuthenticationFailedException..

please help

thanks in advance
Comment by chaitanya - March 04, 2011 @ 6:21 am
worked for me, after setting the internet permission on. Thank you.
Comment by prashant sharma - February 28, 2011 @ 6: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 @ 5:52 am
this code is not working for hotmail and yahoo. how this possible?
Comment by kamran - February 23, 2011 @ 5:22 am
Thanks a lot, that was awesome :D. Exactly what i needed
Comment by MrMaffen - February 17, 2011 @ 1: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 27, 2011 @ 7:08 pm
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 @ 5: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 @ 5:59 pm
Thanks its working now!!
Good Work!!
Comment by Deepanshu - January 19, 2011 @ 3: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 @ 12: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 @ 1: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 05, 2011 @ 8:24 pm
hey please tell me how to give the path of internal storage to send a file
Comment by rakshith - January 05, 2011 @ 12: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 @ 3:11 pm
Fantastic stuff. Thanks for taking the time to post this.
Comment by owen - January 01, 2011 @ 9:48 pm
hey please help, the mail not delivered
Comment by rakshith - December 28, 2010 @ 12:02 pm
Awesome, thank you! This works perfectly!
Comment by mo - December 21, 2010 @ 4:57 pm
please send totla source.zip file
Comment by kiran - December 17, 2010 @ 1: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 @ 6:40 pm
Great stuff! Tested it a few minutes ago, and it does work, even with attachments!
Comment by Finkle - November 28, 2010 @ 2: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 @ 12: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 @ 6: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 @ 1: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 @ 1: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 28, 2010 @ 9:21 pm
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 @ 4: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 23, 2010 @ 11:06 pm
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 @ 1: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 @ 1:00 pm
Can this be done on the iphone???
Comment by mark - July 17, 2010 @ 5:25 pm

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

captcha