December 22, 2014

It's In The Mail

One popular topic recently has been how to send emails from an Android application. You have two options: the painful and not recommended way, and the other way.

The painful and not recommended way is to send the email yourself. This would require you find a suitable SMTP client library for Java (e.g., JavaMail), get it working on Android, provide a UI for your users to provide their SMTP-sending credentials (server, SMTP authentication, etc.), then send the messages. Getting all of this to work properly is not exactly trivial. Combine that with the fact that users now have to enter email information in multiple places (your app and the built-in Email/Google Mail apps), and you can see why this approach has its issues.

There is another way. As with many Android topics, the light was initially shown by Peli and OpenIntents; I’m merely adding a few additional watts on the topic.

You can use an Intent to send an email, via one of the built-in email applications. The plus side is that the user is in full control over which account is used to send the email and can edit the email before delivery. The minus side is that you cannot use this approach to send emails behind the user’s back…which, for some, is actually a plus.

Without further ado, here’s a trivial mail-sending activity:

[sourcecode language=”java”]
public class EmailHitSample extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Intent msg=new Intent(Intent.ACTION_SEND);
String[] recipients={“[email protected]”};
String[] carbonCopies={“[email protected]”};

msg.putExtra(Intent.EXTRA_EMAIL, recipients);
msg.putExtra(Intent.EXTRA_CC, carbonCopies);
msg.putExtra(Intent.EXTRA_TEXT, “This is the email body”);
msg.putExtra(Intent.EXTRA_SUBJECT, “This is the email subject”);
msg.setType(“message/rfc822″);
startActivity(Intent.createChooser(msg, “This is the chooser title”));

finish();
}
}
[/sourcecode]

The Intent we use has an action of ACTION_SEND. Combine that with a MIME type of “message/rfc822″, and Android knows that you are trying to send an email message.

The guts of the email — as much as you want to fill in with your application, anyway — can be handled by a series of extras. The subject is supplied by EXTRA_SUBJECT, and the message body via EXTRA_TEXT. EXTRA_EMAIL is the recipient list, as a String array. A simillar String array can be used with EXTRA_CC for those being CC’d on the message, or EXTRA_BCC for those being BCC’d on the message.

(I’d explain to our younger readers how “CC” refers to carbon copy, and how I even remember actually using carbon paper to make carbon copies of typewritten documents, but probably then I would have to beat some snarky whipper-snappers soundly with my cane, so I won’t talk about any of that.)

The preferred way to send such an Intent is to wrap it in an ACTION_CHOOSER Intent. This will, if applicable, bring up a “chooser” window for the user to pick an application to use to process the Intent, in case there are several activities set up to handle ACTION_SEND Intents for the listed MIME type. If there is only one such activity, then the chooser window will be skipped and the Intent will be routed to the one available choice. The easiest way to construct such a chooser is to use the static createChooser() method on Intent, which takes both the “real” Intent and a title to use on the chooser window, and returns an ACTION_CHOOSER Intent.

So, after contstructing all of that, we shoot off our chooser Intent, then close up this activity. Of course, most applications would be sending emails from deeper inside a real application, but in this case, we may as well just close up shop. Since startActivity() is a fire-and-forget method, we can safely finish() our activity and let our email Intent wind its way through Android. Eventually, a message composition window will appear, with our supplied data already filled in, so the user can just adjust the contents as needed and send off the message.



  • http://www.swap-card.com dileep

    Thanks a lot Marks Murphy.Few days back i had mail u to write a tutorial on sending email.And u have written.Now i will check this code.
    Once again u have proved it that u r always there to help android beginners.
    Thanks
    dileep

  • Sandeep

    Thannks Mark.
    But it will be more useful if u will show that how to use this code in application.In my application user will send email request to someone.For that i have created a UI .In edit box user will enter email id.When user will click the send button then message should go to that particular id.
    So,please enlighten on this also.
    Thanks .

  • Todd A

    I keep getting “No Applications Can Perform This Action”. Seems to be a popular error message on various forums. Some people seem to get past it via the setType method, but that doesn’t fix mine. Any ideas ?

  • http://commonsware.com/Android/ Mark Murphy

    @Todd

    If you are trying this on the emulator, you may not have any email apps installed. See if you can get the APK for K-9 in the emulator. Or, try it on a G1.

  • http://michang05.blogspot.com Mike

    Hmm was that already in release sdk 1 before?
    I did made an email sending app that also has CC on it, but i used apache commons and some socket programming to it and it worked!

    ill check that code then!

  • Rahul

    Hello Mark,

    Thank you very much for the code…But i am not able to run that code in my Android Emulator.I keep getting “No Applications Can Perform This Action”.I have K9 mail client installed and configured in my emulator.But still i am getting the same error.I dont have a G1 with me .It would be really good if you can help me and many others as how to make this code run in an Emulator.

  • dileep

    Hi Mark
    I am using android emulator ver 1.0 r2.In r2 built in email client is dere.BUt I am getting error that no applications can perform this action.
    So,please guide us that how to use this code in emulator.?

  • http://michang05.blogspot.com Mike

    Not working in K-9 and in the emulator native Email app

  • GeneralGDA

    setType(“text/plain”) seems to be working well.

  • mikele

    Thanks for this article, it is clear and sound and
    helped me to understand text sending, the only problem I
    have is that startActivity does not send the email automatically,
    instead this activity brings up the K9 application where I have to go menu -> send, so is it possible to send an email from the code, without bringing up the application….

    thanks in advance

  • http://commonsware.com/Android/ Mark Murphy

    @mikele:

    You would need to use your own SMTP code for that.

  • mikele

    How come K9 in my emulator reads EXTRA_TEXT and EXTRA_SUBJECT, and doesn’t read EXTRA_EMAIL, i.e. when I run my application K9 client pops up and “To” is empty, actually its written To :) Subject is: This is the email subject, Body is: This is the email body, which is OK…

  • Jonathan

    Hi, The mail contains html format, which make with intent.extra_text?, only text, thanks

  • gopal

    I have tried but the email is not send.My code is :

    /**
    * Copyright Sunit Katkar – 2008.
    * http://sunitkatkar.blogspot.com/
    */
    package com.examples.sendmail;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    /**
    * Android application to send an email programmatically.
    *
    * Note: You are FREE to use this application for your personal use. For
    * example, using this code as a learning or teaching aid is ok. If you can, please
    * give me some credit.
    * Please do
    * not
    use it for commercial purposes like creating a product for
    * redistribution, etc.
    *
    * I cannot guarantee that your Android OS powered phone will not crash by using
    * this example code. And, all the usual legal yadda yadda applies. :)
    *
    * If you come across a better way to write this code, please let me know.
    *
    * @author Sunit Katkar ({@link http://www.vidyut.com/sunit})
    * @version 1.0
    * @since December 2008
    *
    */
    public class SendMail extends Activity {

    private EditText emailTo;
    private EditText emailSubject;
    private EditText emailBody;
    private Button btnSend;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Get handle to the text edit and button widgets
    emailTo = (EditText) findViewById(R.id.editTxtTo);
    emailSubject = (EditText) findViewById(R.id.editTxtSubject);
    emailBody = (EditText) findViewById(R.id.editTxtBody);
    btnSend = (Button) findViewById(R.id.btnEmailSend);

    // Attach a click listener to detect button click
    btnSend.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    if (v.getId() == R.id.btnEmailSend) {
    sendEmail();
    }
    }
    });
    }

    /**
    * Method to send email
    */
    protected void sendEmail() {
    // Setup the recipient in a String array
    String[] mailto = { emailTo.getText().toString() };
    //String[] ccto = { “[email protected]” };
    // Create a new Intent to send messages
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    // Add attributes to the intent
    sendIntent.putExtra(Intent.EXTRA_EMAIL, mailto);
    //sendIntent.putExtra(Intent.EXTRA_CC, ccto);
    sendIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject.getText()
    .toString());
    sendIntent.putExtra(Intent.EXTRA_TEXT, emailBody.getText().toString());
    sendIntent.setType(“message/rfc822″);
    sendIntent.setType(“text/plain”);
    startActivity(Intent.createChooser(sendIntent, “Please pick your preferred email application”));
    }
    }

    Is any Smtp desc is required.

    Please help me.

  • Raj

    Hi All,
    Does any one knows how to include sender's email in the email body (EXTRA_TEXT).
    e.g. If my user recommends my application to his/her friend thru email id ([email protected]), I would like to populate an auto filled message with the sender's email id in it.

    Thanks in advance,
    Raj

  • http://www.icommuteless.com sheik ahmed

    Hi ,
    i wanna know is it possible to send market link(market://details?id=com.packgename.appname) in the mail , that would direct user to the application. i was not able to send using <href –> tag as we do in html . Kindly guide on this issue . kindly let me know if the Q is not clear .
    thank you .. ur tutorials are always helpful for the developers and learners like me ..

    regards
    Sheik

  • http://syabac.student.ipb.ac.id syabac

    the code is not readable clearly..

  • sankar.G

    i am getting a alert like no application can perform this action.and i cant able to send the mail in emulator.

  • Sergio

    Is there a way to read emails programmatically?

  • subduedjoy

    Thanks. I too am getting the No Applications Can Perform This Action error and will look for an email app to install on the emulator.

    BTW, I too remember carbon copies. But that doesn’t necessarily mean I’m old. They still have them in checkbooks.

  • Pingback: Homepage

  • Pingback: acne treatment for african americans

  • Pingback: Moriah Olivas

  • Pingback: car insurance quotes

  • Pingback: online payday loans

  • Pingback: εγκατασταση φυσικου αεριου

  • Pingback: codes promos amazon

  • Pingback: found here

  • Pingback: δισκοι

  • Pingback: istanbul property

  • Pingback: Essex Junction