I am trying to create a mail sending application in Android.
If I use:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
This will launch the built-in Android application; I'm trying to send the mail on button click directly without using this application.
Those who are getting
ClassDefNotFoundError
try to move that Three jar files to lib folder of your Project,it worked for me!!All the code provided in the other answers is correct and is working fine, but a bit messy, so I decided to publish a library (still in development though) to use it in a easier way: AndroidMail.
You have just to create a MailSender, build a mail and send it (already handled in background with an AsyncTask).
You can receive a notification for the email sent and it has also the support for different Recipients types (TO, CC and BCC), attachments and html:
You can get it via Gradle or Maven:
Please let me know if you have any issue with it! :)
SMTP
Using SMTP is one way to go, and the others have already pointed out ways how to do it. Just note that while doing this, you completely circumvent the built in mail app, and you will have to provide the address of the SMTP server, the user name and password for that server, either statically in your code, or query it from the user.
HTTP
Another way would involve a simple server side script, like php, that takes some URL parameters and uses them to send a mail. This way, you only need to make an HTTP request from the device (easily possible with the built in libraries) and don't need to store the SMTP login data on the device. This is one more indirection compared to direct SMTP usage, but because it's so very easy to make HTTP request and send mails from PHP, it might even be simpler than the direct way.
Mail Application
If the mail shall be send from the users default mail account that he already registered with the phone, you'd have to take some other approach. If you have enough time and experience, you might want to check the source code of the Android Email application to see if it offers some entry point to send a mail without user interaction (I don't know, but maybe there is one).
Maybe you even find a way to query the users account details (so you can use them for SMTP), though I highly doubt that this is possible, because it would be a huge security risk and Android is built rather securely.
In order to help those getting a Network On Main Thread Exception with an SDK Target >9. This is using droopie's code above but will work similarly for any.
You can use AsyncTask as below
I tried using the code that @Vinayak B submitted. However I'm getting an error saying: No provider for smtp
I created a new question for this with more information HERE
I was able to fix it myself after all. I had to use an other mail.jar and I had to make sure my "access for less secure apps" was turned on.
I hope this helps anyone who has the same problem. With this done, this piece of code works on the google glass too.