How to send email from Android application Android 16.10.2016

android_email.png

In this tutorial, you will learn how to send an email to someone from your Android application. To send email from Android we will use Intent.ACTION.SEND to call installed email client. If you do not have any email clients in the phone, this email can’t be sent. As alternative, you can use Javamail API to send email using SMTP.

Android provides us some fields that can be used to complete some elements of an email client (for instance recipients, subject etc). These fields have to be attached to the Intent as extra data:

  • EXTRA_BCC: email addresses for blind carbon copy
  • EXTRA_CC: email addresses for carbon copy
  • EXTRA_EMAIL: email addresses for recipients
  • EXTRA_HTML_TEXT: supply an alternative to EXTRA_TEXT as HTML formatted text
  • EXTRA_STREAM: URI holding a stream of data supplying the data that are sent
  • EXTRA_SUBJECT: the subject of an email
  • EXTRA_TEXT: the message body of the email
  • EXTRA_TITLE: the title that is shown when the user has to choose an email client

Following snippet is example of preparation and sending email

sendEmailButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String toEmail = "to@server.com";
        String subject = "Test";
        String message = "Hello world!";

        Intent mailIntent = new Intent(Intent.ACTION_SEND);
        mailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{toEmail});
        mailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
        mailIntent.putExtra(Intent.EXTRA_TEXT, message);
        mailIntent.setType("message/rfc822");
        startActivity(Intent.createChooser(mailIntent, "Send Email Via"));
    }
});

You can also add a file attachment to your email in Android like this

mailIntent.putExtra(Intent.EXTRA_STREAM, FILE_URI);

Also you can use EmailInputView as an enhanced EditText with easy ability to get valid email from user. An error message will appear for invalid emails.