20

I have seen multiple threads in this site discussing about sending email with attachments in android. I tried every methods discussed here, here and here.

I am creating a csv file via code and saving this file to android internal storage. Then I want to send this file as attachment in an email. Well, the email is being sent, I am getting it without attachment. This is what I have done.

String columnString         =   "\"Person\",\"Gender\",\"Street1\",\"PostOfice\",\"Age\"";
String dataString           =   "\"" + currentUser.userName +"\",\"" + currentUser.gender + "\",\"" + currentUser.street1 + "\",\"" + currentUser.poNumber.toString() + "\",\"" + currentUser.age.toString() + "\"";
String combinedString       =   columnString + "\n" + dataString;
File file                   =   new File(this.getCacheDir()+ File.separator + "Data.csv");
try {
    FileOutputStream out    =   new FileOutputStream(file);
    out.write(combinedString.getBytes());
    out.close();
} catch (IOException e) {
    Log.e("BROKEN", "Could not write file " + e.getMessage());
}   
Uri u1                      =   Uri.fromFile(file);

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Person Details");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/richtext");
startActivity(sendIntent);

I tried changing mime settings to "text/html" and "text/richtext" etc. But no luck yet. Can anyone tell me what I am doing wrong?

Community
  • 1
  • 1
Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
  • Have you tried printing the URI before putting it in intent ? – Karan Mar 23 '11 at 05:40
  • Yes, And I got file:///Data.csv which I think what it should be..is it? – Krishnabhadra Mar 23 '11 at 05:45
  • Nope...you should use sdcard or something else. I don't think that application can create files in root directory. Btw you can verify that using adb shell. – Karan Mar 23 '11 at 05:49
  • How is that, can u elaborate a bit? Also SDCard means external memory, right? What if I not have one? – Krishnabhadra Mar 23 '11 at 05:53
  • Have you seen whether file is created or not ? – Karan Mar 23 '11 at 05:55
  • No. How can I check that? I am using MAC I mounted the device in finder and searched for it but cant see the file. But I presume internal storage doesnt mount on finder. – Krishnabhadra Mar 23 '11 at 06:06
  • I am now trying to save to SDCard as you suggested.. – Krishnabhadra Mar 23 '11 at 06:06
  • 1
    You can also try getCacheDir() and store the data there. You can get details here [http://developer.android.com/reference/android/content/Context.html#getCacheDir%28%29]. – Karan Mar 23 '11 at 06:07
  • k..I am trying that now..thanks..will comeback with result..:) – Krishnabhadra Mar 23 '11 at 06:13
  • I tried getCacheDir() and edited my question? Still no attachment.. – Krishnabhadra Mar 23 '11 at 06:27
  • How can I see whether file is created or not? – Krishnabhadra Mar 23 '11 at 06:34
  • hi krishnabhadra ..i am also facing same problem can you help me pls.how to write data to csv file and how can i see that file means in storage location...i am trying to save .csv file to my sdcard ...so can you help me how you over come from that problem i tried ur solution given below but it is giving error pls see it what i did http://pastebin.com/9ZQABpJj vv thanks – SRam Jul 27 '11 at 11:45
  • @sourabh, The error says variable file is null..That means **file = new File(dir, "Data.csv");** is returning null..Put a breakpoint in onCreate see why it gets null...Also make sure you have not connected your phone to PC...That is very important – Krishnabhadra Jul 27 '11 at 12:17

5 Answers5

53

Thanks for everyone who tried to help..After taking a full day I have send an email from my app with attachment..This is the working code..

String columnString =   "\"PersonName\",\"Gender\",\"Street1\",\"postOffice\",\"Age\"";
String dataString   =   "\"" + currentUser.userName +"\",\"" + currentUser.gender + "\",\"" + currentUser.street1 + "\",\"" + currentUser.postOFfice.toString()+ "\",\"" + currentUser.age.toString() + "\"";
String combinedString = columnString + "\n" + dataString;

File file   = null;
File root   = Environment.getExternalStorageDirectory();
if (root.canWrite()){
    File dir    =   new File (root.getAbsolutePath() + "/PersonData");
     dir.mkdirs();
     file   =   new File(dir, "Data.csv");
     FileOutputStream out   =   null;
    try {
        out = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            out.write(combinedString.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Uri u1  =   null;
u1  =   Uri.fromFile(file);

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Person Details");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);

Also If you have mounted your phone SDCard in the machine , this code wont work. Only one can access SDCard at one time. So in that case unmount your SDCard from computer and try..Thanks to the guy who answered here..Also make sure you have bought permission to write to external Storage in your manifest file...

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

Hope it helps someone...Thanks for everyone who tried to help..

Community
  • 1
  • 1
Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
  • actually your code work on android device but not for emulator when i run app on emulator it force close and giving nuul pointer exception at u1 = Uri.fromFile(file);.could you pls tell me the resion why pls – SRam Jul 27 '11 at 12:57
  • 1
    If you want to share private files (i.e., stored internally) then you must use a ContentProvider. see this link: http://stackoverflow.com/a/9645127/1172181 – Luis Mar 10 '12 at 09:08
4

This Code will help you out

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonSend = (Button) findViewById(R.id.buttonSend);

    textTo = (EditText) findViewById(R.id.editTextTo);
    textSubject = (EditText) findViewById(R.id.editTextSubject);
    textMessage = (EditText) findViewById(R.id.editTextMessage);

    buttonSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            String to = textTo.getText().toString();
            String subject = textSubject.getText().toString();
            String message = textMessage.getText().toString();

            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("plain/text");
            File data = null;
            try {
                Date dateVal = new Date();
                String filename = dateVal.toString();
                data = File.createTempFile("Report", ".csv");
                FileWriter out = (FileWriter) GenerateCsv.generateCsvFile(
                        data, "Name,Data1");
                i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(data));
                i.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
                i.putExtra(Intent.EXTRA_SUBJECT, subject);
                i.putExtra(Intent.EXTRA_TEXT, message);
                startActivity(Intent.createChooser(i, "E-mail"));

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });
}

public class GenerateCsv {
    public static FileWriter generateCsvFile(File sFileName,String fileContent) {
        FileWriter writer = null;

        try {
            writer = new FileWriter(sFileName);
            writer.append(fileContent);
                         writer.flush();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            try {
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return writer;
    }
}

Add this line in AndroidManifest.xml file:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission
t0mm13b
  • 34,087
  • 8
  • 78
  • 110
RajeshVijayakumar
  • 10,281
  • 11
  • 57
  • 84
  • 1
    Hi @ADR I can't seem to get the above code to work in my app. It doesnt send an attachment to the receipient. When I create the email it has a dummy file attached which has no information in it. In the code it mentions that "filename" and "out" are not used "The value of the local variable filename is not used". – PaulH Jun 26 '13 at 09:28
  • Setting the correct mime type for the file works. i.setType("plain/text"); – Ahesanali Suthar Apr 05 '19 at 03:05
3

Try

sendIntent.setType("message/rfc822");
Jeremy Edwards
  • 14,620
  • 17
  • 74
  • 99
2

For internal storage files, you need to make the file readable:

shareFile.setReadable(true, false);

pstoppani
  • 2,531
  • 1
  • 20
  • 20
1

Here is the code for attachment of csv file in mail (Its working code): MyCsvFile.csv" should be present in your Internal/External memory of phone.

For More Look into this :https://stackoverflow.com/a/48643905/8448886

Below is the code for attachment of csv file into mail :

String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv


button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                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 file = new File(csv);
                Uri uri = Uri.fromFile(file);
                emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
                startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));
            }
        });
Abhishek kumar
  • 4,347
  • 8
  • 29
  • 44