Android使用字符串附件发送邮件

我有一个
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"));

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

最佳答案

This code saves you from adding a manifest uses permission to read from external sd card. It creates a temp in files directory on your app private directory then creates the file with the contents of your string and allows read permission so that it can be accessed.

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

This should be called whenever you dont need the file anymore.

BufferedWriter bw = null;
File tempData = new File(getFilesDir(),"tempFile");
if (tempData.exists()) {
    tempData.delete();
}
点赞