【问题标题】:Android - How to attach a file to mail without using content providersAndroid - 如何在不使用内容提供程序的情况下将文件附加到邮件
【发布时间】:2013-12-13 10:26:17
【问题描述】:

您好,我正在尝试创建一个应用程序来创建一个 word 文件并通过邮件发送它。 到目前为止,我设法创建了文件,以及调用邮件应用程序选择器的必要意图, 但是我遇到了两个问题:

1)我收到一个列表,其中包含的不仅仅是邮件程序 - wifi、BT 等也显示

2)如果我选择 gmail,则在 gmail 中将文件名作为附件查看,但是在发送后我没有收到任何文件。 我尝试使用 URI 而不是 Uri,但是当 gmail 尝试附加文件时,我得到了 javaNullExeption。

问题是:如何发送附件(如果可能,不使用像内容提供者这样的复杂类)

我使用的代码:

创建文件:

public void saveFile(String fileName,String content) throws IOException,FileNotFoundException
    {
        FileOutputStream fos = getContext().openFileOutput(fileName, Context.MODE_WORLD_READABLE);
        fos.write(content.getBytes());
        fos.close();    
    }

发送:

public void sendAsMail(Context context,String fileName)
{
    File file = new File(getContext().getFilesDir().getAbsolutePath()+"/"+fileName);
    //file.setReadable(true);
    //URI myUri = file.toURI();
            Uri myUri=Uri.fromFile(file);
    Intent emailIntent = new Intent (Intent.ACTION_SEND);
    emailIntent.setType("text/plain");
    emailIntent.putExtra(Intent.EXTRA_EMAIL,"");
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, context.getResources().getString(R.string.free_search_mail_subject));
    emailIntent.putExtra(Intent.EXTRA_TEXT,context.getResources().getString(R.string.free_search_mail_content));
    emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);
    context.startActivity(Intent.createChooser(emailIntent, "Send the file using:"));
}

我测试了文件以查看它是否正确创建(使用扫描仪打印),这似乎不是问题

【问题讨论】:

  • 尝试检查 sendAsMail 中是否存在文件:file.exists()。您也可以尝试使用 myUri.toString() 记录 Uri 内容以检查是否正常。
  • 我测试它我得到文件存在:I/System.out(30122): true 并且 uri 是:file:///data/data/com.project.mishnayot/files/print .doc 但由于某种原因它仍然不起作用

标签: java android email email-attachments


【解决方案1】:

第一个检查文件是否创建。如果已创建,请尝试使用此代码:

public static void sendAsMail(File file, Context econtext) {
    try {
        final Intent emailIntent = new Intent(
                android.content.Intent.ACTION_SEND);
        emailIntent.setType("text/*");
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                new String[] { "" });
        emailIntent.putExtra(android.content.Intent.EXTRA_CC,
                new String[] {});
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "FROM Sample");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "HI");
        emailIntent.putExtra(android.content.Intent.EXTRA_STREAM,
                Uri.parse(file.toURI().toString()));
        mContext.startActivity(emailIntent);
    } catch (Exception e) {
    }
}

如果它不起作用,请发表评论。

【讨论】:

  • o 这行得通,出于某种原因 emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.toURI().toString())); emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);没有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 2010-12-22
  • 1970-01-01
  • 2015-06-20
  • 2014-05-18
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多