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 copyEXTRA_CC
: email addresses for carbon copyEXTRA_EMAIL
: email addresses for recipientsEXTRA_HTML_TEXT
: supply an alternative to EXTRA_TEXT as HTML formatted textEXTRA_STREAM
: URI holding a stream of data supplying the data that are sentEXTRA_SUBJECT
: the subject of an emailEXTRA_TEXT
: the message body of the emailEXTRA_TITLE
: the title that is shown when the user has to choose an email clientFollowing 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.