How to Send an Email with a File Attachment in Android

How to send an email with a file attachment in Android

Use the below code to send a file within a email.

String filename="contacts_sid.vcf"; 
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// 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, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(emailIntent , "Send email..."));

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..."));
}

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

couldn't attach file send email android 11

I have attached the image successfully in email i will give you a code

convert your URI to file

 private void Share(File savepath) {

if (savePath != null) {

Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", savePath);

Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"fake@fake.edu"});
i.putExtra(Intent.EXTRA_SUBJECT,"On The Job");
//Log.d("URI@!@#!#!@##!", Uri.fromFile(pic).toString() + " " + pic.exists());
i.putExtra(Intent.EXTRA_TEXT,"All Detail of Email are here in message");
i.putExtra(Intent.EXTRA_STREAM,uri);
i.setType("image/png");
context.startActivity(Intent.createChooser(i,"Share you on the jobing"));

}

how to add provider in XML path
first, you have to create an XML resource folder then create an XML resource file
after pasting this code

<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>

then also add-in manifest

<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>

file provider in xml

decalre in manifest

Send email with attachment from internal storage


I'm assuming you are trying to send the file as an email attachment
using intents.

The reason why the file is empty is that the email app does not have
access to the file in /data/data/package_name/myfile_name, due to
Androids security model (the /data/data/package_name directory is
private to your app).

In order to add the file as an attachment, you need to write it to
public storage (such as the SD card) so the email app can access it.

Unable to attach an attachment with email in android

Check this :

Email with Attachment and Example

Hope this helps.



Related Topics



Leave a reply



Submit