Android Intent for Sending Email with Attachment

Sending an email with attachments programmatically on Android

Official documentation with Kotlin snippets is here: https://developer.android.com/guide/components/intents-common#ComposeEmail

I think your problem is that you are not using the correct file path.

The following works for me:

Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"email@example.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
emailIntent.putExtra(Intent.EXTRA_TEXT, "body text");
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "temp/attachement.xml";
File file = new File(root, pathToMyAttachedFile);
if (!file.exists() || !file.canRead()) {
return;
}
Uri uri = Uri.fromFile(file);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));

EDIT: Requesting access to storage just to share a file private to your app is probably not a good idea. Fortunately, after a little configuration, it's very easy to share a file from your app private storage. See this guide: https://developer.android.com/training/secure-file-sharing/setup-sharing

If you share a file that is on external storage, you also need to give the user permission via a manifest file like below

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Android\Intent: Send an email with image attachment

Try below code...

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{strEmail});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Test Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "From My App");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///mnt/sdcard/Myimage.jpeg"));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));

Android Email intent with multiple attachments

I've solved it. When the images are chosen they are put into the ArrayList "userSelectedImageUriList" in onActivityResult.

Instead of parsing this list in the sendReport method, I just add this list to the intent.

The working method looks like this:

public void sendReport(Context context) {
EditText nameField = (EditText)findViewById(R.id.EditTextName);
EditText emailField = (EditText)findViewById(R.id.EditTextEmail);
EditText locationField = (EditText)findViewById(R.id.EditTextLocation);
EditText dateField = (EditText)findViewById(R.id.EditTextDate);
EditText bodyField = (EditText)findViewById(R.id.EditTextBody);

if(!nameField.getText().toString().matches("") && !emailField.getText().toString().matches("") && !locationField.getText().toString().matches("") && !dateField.getText().toString().matches("") && !bodyField.getText().toString().matches("")) {
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("report_email", emailField.getText().toString()).apply();
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("report_name", nameField.getText().toString()).apply();

String emailBody = "Name: "+nameField.getText()+"\n\n";
emailBody += "Location: "+locationField.getText()+"\n\n";
emailBody += "Time: "+dateField.getText()+"\n\n";
emailBody += "Description: "+bodyField.getText();

Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);

// set the type to 'email'
emailIntent.setType("text/plain");
String to[] = {emailField.getText().toString()};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);

// the attachment - ArrayList populated in onActivityResult
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, userSelectedImageUriList);

// the mail
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report);
emailIntent.putExtra(Intent.EXTRA_TEXT, emailBody);

startActivity(Intent.createChooser(emailIntent , "Send with..."));
//finish();
} else {
Toast.makeText(this, getString(R.string.field_error), Toast.LENGTH_SHORT).show();
}
}

How to send text file via email as an attachment - Android?

If your targetSdkVersion >= 24, then we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.

Step-1:
Add below code in AndroidManifest.xml file.

        <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/file_paths" />
</provider>

Step-2

Create a xml folder inside res folder. And create a file namely file_paths.xml because look at above code inside <meta-data>.

file_paths.xml

<paths>
<external-path name="external_files" path="."/>
</paths>

Step-3
Now you could save file inside your package.private folder and you can share file uri saved inside this folder to other app, for example gmail app as an attachment. Now your method looks like:

    private void saveData() {
String filename = "eulerY.txt" ;
//FileOutputStream fos_FILE_eulerY = null;
File externalFilesDirectory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File textFile = new File(externalFilesDirectory,filename);
String message = "hello";
try {
//fos_FILE_eulerY = openFileOutput(textFile.getAbsolutePath() , MODE_PRIVATE);
//fos_FILE_eulerY.write(message.getBytes());
FileWriter writer = new FileWriter(textFile);
writer.append(message);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e){
e.getLocalizedMessage();
}

// export data
sendEmail (textFile);
}

private void sendEmail (File file){
//File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
//Uri path = Uri.fromFile(filelocation);
//FileProvider.getUriForFile(it, "${it.packageName}.provider", file)
Uri fileUri = FileProvider.getUriForFile(this,getPackageName()+".provider",file);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String[] to = {"asd@gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, fileUri);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(emailIntent , "Send email..."));
}


Related Topics



Leave a reply



Submit