生成csv文件和电子邮件作为附件

时间:2013-01-21 07:39:27

标签: android android-intent email-attachments

我正在尝试生成Csv文件,同时将其作为附件发送到电子邮件中。它通过电子邮件发送时显示附件,但问题是,当我检查收件箱时,我只找到没有附件的电子邮件。我会恭喜你的帮助。

这是我试过的代码

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

1 个答案:

答案 0 :(得分:0)

可以看出,您的GenerateCsv无法正常运行,您必须导入csv库。在你的代码中没有任何。要下载,请检查:Csv library

另见:Read/Write csv

和清单中的权限:

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