Birrel
Birrel

Reputation: 4834

Android, .txt email attachment not sending via intent

I'm testing out creating a .txt file, and then sending it as an email attachment, via an intent.

Creating the .txt File

    try {
        String fileName = "testFileName.txt";
        File root = new File(Environment.getExternalStorageDirectory(), "testDir");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, fileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append("Testing email txt attachment.");
        writer.flush();
        writer.close();
        sendEmail(gpxfile.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }

Sending the email

protected void sendEmail(String fileName){
    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_SUBJECT, "Test subject");
    i.putExtra(Intent.EXTRA_TEXT, "This is the body of the email");
    i.putExtra(Intent.EXTRA_STREAM, Uri.parse(fileName));
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
}

And this all seems to work fine. It opens up the email client, with the subject, body and attachment all visible

Composing email

And sends just fine, indicating there is an attachment

Sent email

But when I open gmail, there is no attachment shown

Gmail, no attachment

Same story when I view the email

Gmail, detailed, no attachment

And viewing the email on the phone, from within the "Sent" folder, also shows no attachment

Android, sent, no attachment

The code is a copy and paste from multiple different posts on SO, and seemingly they are not having any issues. Where is the file going? Is it being stopped by gmail? Or not sending at all? Does the file not exist?

Note: I do have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> set in the manifest.

Thanks in advance.

Upvotes: 3

Views: 1794

Answers (1)

Birrel
Birrel

Reputation: 4834

The problem was with the file path. Made the following changes:

sendEmail(gpxfile); // This is the file itself, not the file path

Then actually sending the email:

protected void sendEmail(File file){
    Uri path = Uri.fromFile(file); // This guy gets the job done!

    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_SUBJECT, "Test subject");
    i.putExtra(Intent.EXTRA_TEXT, "This is the body of the email");
    i.putExtra(Intent.EXTRA_STREAM, path); // Include the path
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
}

Upvotes: 3

Related Questions