Search code examples
androidemail-attachments

android send public storage file via email attachment


This is a follow-on to my previous post1.

To recap, I want MyApp to send its data file to a specified e-mail address using an Intent. I now have the following code for this:

public void onClickSend(View v) {
    Intent i = new Intent(android.content.Intent.ACTION_SEND);
    String Email[] = { "my.address@gmail.com" };
    i.putExtra(android.content.Intent.EXTRA_EMAIL, Email);
    i.putExtra(android.content.Intent.EXTRA_SUBJECT, "Report");
    i.setType("text/plain");

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
    File f = new File(path, _tdSource.GetFileName());

    Uri sUri = FileProvider.getUriForFile(v.getContext(), "org.myorg.myapp.fileprovider", f);
    i.setData(sUri);
    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    i.putExtra(Intent.EXTRA_STREAM, sUri);
    startActivity(i);
}

the manifest file for MyApp contains the following:

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/AppTheme">
    ...
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SubActivity"></activity>
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="org.myorg.myapp.fileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>
</application>

MyApp hits an exception on the call to FileProvider.getUriForFile(). Oddly enough, the exception is java.lang.reflect.InvocationTargetException and is caught within AppCompatViewInflater.onClick().

I have no idea what I'm doing wrong or where to go with this...


Solution

  • Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, address);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); // attachment
    intent.setType("message/rfc822"); // message content type
    startActivity(Intent.createChooser(intent, "Share via");