Friday, February 25, 2011

Sending Emails on Android, Take 2

A while back, I wrote a post about how to send specifically send only emails on Android. Unfortunately, the solution I posted does not work 100% of the time.

My previous solution was a hack and (as hacks are wont to do) it came back to bite my in the ass. It turns out that some email programs have buggy implementations of the mailto protocol. This led us to some users not getting the body content when using the mailto trick.

The correct solution is to use the normal ACTION_SEND intent, but setting the type to "message/rfc822", so only programs that implement emails will accept the intent.

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, "");
intent.putExtra(Intent.EXTRA_SUBJECT, "A Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Here's my message.");

Not only does this work more often than my hack, but it's far more elegant, too.

One other choice I've made recently is to just use startActivity() on the original intent instead of creating a chooser first. That way, the user can opt for a default email program to use instead of being asked each time which app should handle the intent.

1 comment:

  1. Your solution here is quite nice except when I ran the code it popped up a menu of email choice together with Bluetooth and Evernote... But still this is the closet solution to my target, thanks Daniel!