Android从字符串发送带有附件的邮件

Bar*_*osa 4 string email android attachment

我有一个HTML字符串,我想将其作为文件附加到邮件中。我可以将此字符串保存到文件中并附加它,但是我想在不将其保存到文件中的情况下进行操作。我认为应该有可能,但我不知道该怎么做。这是我的代码:

String html = "<html><body><b><bold</b><u>underline</u></body></html>";
Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(html));

// this is where I want to create attachment
intent.putExtra(Intent.EXTRA_STREAM, Html.fromHtml(html));

startActivity(Intent.createChooser(intent, "Send Email"));
Run Code Online (Sandbox Code Playgroud)

如何将字符串作为文件附加到邮件中?

ger*_*uez 5

此代码使您免于添加清单清单使用权限以从外部SD卡读取数据。它在您的应用程序专用目录的files目录中创建一个temp,然后使用字符串的内容创建该文件,并允许读取权限,以便可以对其进行访问。

String phoneDesc = "content string to send as attachment";

FileOutputStream fos = null;
try {
        fos = openFileOutput("tempFile", Context.MODE_WORLD_READABLE);
        fos.write(phoneDesc.getBytes(),0,phoneDesc.getBytes().length);
        fos.flush();
        fos.close();
} catch (IOException ioe) {
    ioe.printStackTrace();
}
finally {
    if (fos != null)try {fos.close();} catch (IOException ie) {ie.printStackTrace();}
}
File tempFBDataFile  = new File(getFilesDir(),"tempFile");
Intent emailClient = new Intent(Intent.ACTION_SENDTO, Uri.parse("someone@somewhere.com"));
emailClient.putExtra(Intent.EXTRA_SUBJECT, "Sample Subject";
emailClient.putExtra(Intent.EXTRA_TEXT, "Sample mail body content");
emailClient.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFBDataFile));//attachment
Intent emailChooser = Intent.createChooser(emailClient, "select email client");
startActivity(emailChooser);
Run Code Online (Sandbox Code Playgroud)

每当您不再需要该文件时,都应该调用它。

BufferedWriter bw = null;
File tempData = new File(getFilesDir(),"tempFile");
if (tempData.exists()) {
    tempData.delete();
}
Run Code Online (Sandbox Code Playgroud)

  • 它说“ Context.MODE_WORLD_READABLE”由于安全问题而被弃用。 (3认同)