Friday, March 11, 2011

Send Email from Android Application

One of the most common tasks a developer would like to add to his/her application in order to keep in touch with its users is to allow the user send emails from within the application.

Following the Android Developers Reference for the Intent.ACTION_SEND lacks the documentation you would expect in order to properly send an email (not SMS, Twit, file, image etc...).


In order for you to enforce email submission you need to specify the correct type for the created intent. Normally, you would write something like:
emailIntent.setType("text/plain");
but that would let you choose all kinds of applications for performing tasks that are completely unrelated to sending emails.


This is the snippet I use to send email from my applications. notice the type used to force email application.

private void sendEmail()
{
try
{
Intent emailIntent = new Intent(Intent.ACTION_SEND);

String aEmailList[] = { "some_email@domain.com"};

emailIntent.putExtra(Intent.EXTRA_EMAIL, aEmailList);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Sample Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "");

emailIntent.setType("message/rfc822");

startActivity(Intent.createChooser(emailIntent, "Select Email Application"));
}
catch (Exception ex)
{
Log.e("SendEmail", "Can't send email", ex);
}
}