After tackling the Android Intent send email task, I have a newfound respect for this OS and its intricacies. The methodology is pretty straightforward and relatively simple to implement.
I’ll cover the steps I took and show you how to use Intent to send emails from an Android app (code examples included). Plus, I dedicate a special section to error handling and email testing.
Let’s start coding!
The Intent method is the native way to send email in Android programmatically.
So first, you need to make sure to have an Android project set up in your development environment. Here’s a quick overview of the steps:
like app/src/main
, and it includes: – java/
: Your source code.
– res/
: Resources like layouts, strings, and images.
– AndroidManifest.xml
: Configuration file, where you can set the MainActivity.
Pro Tips:
Now, I’ll use Intent
to invoke an existing email client on the Android device. The Intent
has to be set up using the correct action: ACTION_SEND
or ACTION_SENDTO
. Also, you’ll need the correct data: email address, subject, body, etc.
Note: I’m using Java in the examples below. This tutorial doesn’t cover SMS (optionally or otherwise), only an email message.
The Intent
system allows basic HTML via your Android application. Keep in mind that the final email rendering largely depends on the email client used by the recipient. (e.g. The rendering may look and perform differently on Gmail and Microsoft Outlook)
Pro Tip: You can run your email templates through Mailtrap Email Testing to check for support with the most popular email clients and debug the templates if necessary. I’ll show you how to do it at the end of this article.
Here’s the exemplary snippet for the HTML email:
// Method to send an HTML email to a single recipient without attachment
public void sendEmailSingleRecipient(String recipient, String subject, String htmlBody) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:")); // only email apps should handle this
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient}); // Single recipient
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
// Adding HTML body
emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(htmlBody));
emailIntent.setType("text/html");
startActivity(emailIntent);
}
The method is tailored to a single email recipient, the recipient’s email address is passed a single-element array to the Intent.EXTRA_EMAIL
field. Later, I’ll show how to include BCC for multiple recipients.
And with the startActivity(emailIntent);
intent, any applications that support plaintext messaging will be able to handle this request. Once you have set the type data for the Intent, you can call the startActivity()
method, passing in your Intent.
To include attachments you need to fetch the file from storage and add it as an extra stream to the intent. Check the example below.
// Import necessary classes
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
public class EmailSender extends AppCompatActivity {
public static final int PICK_TEXT_FILE_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button picker = findViewById(R.id.picker);
picker.setOnClickListener(view -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(Intent.createChooser(intent, "Select Text File"), PICK_TEXT_FILE_REQUEST);
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_TEXT_FILE_REQUEST && resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
// Trigger file picker
sendEmailSingleRecipient("ghostdev030823@gmail.com",
"This is a test subject",
"This is a test email body using Android intent", uri);
}
}
}
}
// Method to send an HTML email to a single recipient with an attachment
public void sendEmailSingleRecipient(String recipient, String subject, String body, Uri filePath) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
emailIntent.putExtra(Intent.EXTRA_STREAM, filePath);
emailIntent.setType("message/rfc822"); // only email apps should handle this
startActivity(emailIntent);
}
}
Also, remember to configure the FileProvider
in your Android manifest and resource files to handle file attachments securely.
The correct configuration for the manifest file, particularly for the newer Android versions, is:
<application>
…
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
...
</application>
And in the res/xml/file_paths.xml
, it’s:
<paths>
<external-path name="external_files" path="."/>
</paths>
Configuration notes:
your.authority
with your app’s authority, typically your application’s package name.FileProvider
.For the sake of convenience, I’ll tweak the example above to include multiple recipients. Here’s the updated code.
// Import necessary classes
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import java.io.File;
public class EmailSender {
// Method to send an HTML email to multiple recipients with an attachment
public void sendEmailWithAttachment(String[] recipients, String subject, String htmlBody, File attachmentFile) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:")); // only email apps should handle this
emailIntent.putExtra(Intent.EXTRA_EMAIL, recipients); // Multiple recipients
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
// Check if the attachment is not null and exists
if (attachmentFile != null && attachmentFile.exists()) {
// Add the attachment using FileProvider
Uri uri = FileProvider.getUriForFile(context, "your.authority", attachmentFile);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
}
// Adding HTML body
emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(htmlBody));
emailIntent.setType("text/html");
// Verify that the intent will resolve to an activity
if (emailIntent.resolveActivity(getPackageManager()) != null) {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else {
// Handle the situation where no email client is installed
// Show an error message or a notification
}
}
}
The recipients
parameter is now an array of strings, allowing you to specify multiple email addresses. The rest of the method remains unchanged, supporting both HTML content and file attachments.
Intent
, Uri
, File
, and others.sendEmail
method: This method accepts the recipients’ email addresses, the email subject, the HTML body, and an optional file attachment.Intent.ACTION_SENDTO
with mailto:
to ensure only email apps handle this intent.Intent.EXTRA_EMAIL
and Intent.EXTRA_SUBJECT
.FileProvider
to get a content URI for the file and add it to the intent. This is a secure way to share files between apps starting from Android 7.0 (API level 24). As mentioned earlier, you’ll need to define a FileProvider
in your manifest and create an XML file defining available paths.Html.fromHtml(htmlBody)
to add the HTML formatted text to the email body. The rendering depends on the email client’s capabilities."text/html"
, it can also be "text/plain"
. Here, I’d like to touch upon some functions, commands, and elements that didn’t make it into this tutorial. But, based on your specific use case, you might find them useful.
EditText
, TextView
doesn’t allow user input and is used primarily for displaying static text or text that changes dynamicallyOnClickListener
interface and its onClick
method, you can define what happens when a user clicks on a particular view. onClick
method. When you implement the interface, you have to provide a corresponding implementation. It’s called when a view (with the listener attached) receives a click event. In the exemplary snippets, I didn’t include error handling to avoid bloating the code and help you focus only on the given methodology.
Nevertheless, it’s important to check if there’s an app to handle the email intent. If not, you should handle this gracefully, perhaps by showing an error message. There are two methods to do this.
Note: I won’t be rewriting the whole code, just what can be included under } else {...}
#1 – Simple error snippet
} else {
// No email client is installed, handle this case
Toast.makeText(context, "No email client installed.", Toast.LENGTH_SHORT).show();
}
I trust you found the excerpt about the Android Intent for Sending Emails tutorial enjoyable. To access the full original post, please visit the Mailtrap Blog.