Search code examples
androidandroid-intentemail-attachments

Attach vCard to Email Intent


I am attempting to attach a vCard (*.vcf) to an email intent like so:

Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Shared Contact via the Foo App");

// vcfFile is a *.vcf file on local storage
Uri vCardUri = FileProvider.getUriForFile(this, "com.foo.fileprovider", vcfFile);
emailIntent.setData(vCardUri);
startActivity(emailIntent);

However, the app dies with the following exception:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.SENDTO dat=content://com.foo.fileprovider/external_files/Android/data/com.foo/files/generated.vcf (has extras) }

I have also tried to explicitly set the type like this:

emailIntent.setDataAndType(vCardUri, "text/x-vcard");

However, it also blows up with a:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.SENDTO dat=content://com.foo.fileprovider/external_files/Android/data/com.foo/files/generated.vcf typ=text/x-vcard (has extras) }

Is there a way to attach a vCard to an email intent?


Solution

  • Sharing files is only documented to work with ACTION_SEND. Put the Uri into EXTRA_STREAM. (This might also work with ACTION_SENDTO with some email apps).

    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Shared Contact via the Foo App");
    
    // vcfFile is a *.vcf file on local storage
    Uri vCardUri = FileProvider.getUriForFile(this, "com.foo.fileprovider", vcfFile);
    emailIntent.putExtra(Intent.EXTRA_STREAM, vCardUri);
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    emailIntent.setType("text/x-vcard");
    startActivity(Intent.createChooser(emailIntent, null));