在Android上以编程方式发送带附件的电子邮件

Dig*_* Da 16 email android email-attachments android-intent

我希望实现一个按钮,按下它将打开带有附件文件的默认电子邮件客户端.

我正在关注这个,但是我在startActivity上收到一条错误消息,说它正在期待一个活动参数,而我正在给它一个意图.我使用的是API 21和Android Studio 1.1.0,所以它可能与链接中提供的答案中的注释有关?

这是我作为Android开发人员的第四天,很抱歉,如果我遗漏了一些非常基本的东西.

这是我的代码:

    public void sendFileToEmail(File f){

    String subject = "Lap times";
    ArrayList<Uri> attachments = new ArrayList<Uri>();
    attachments.add(Uri.fromFile(f));
    Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachments);
    intent.setClassName("com.android.email", "com.android.mail.compose.ComposeActivity");

    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

Kin*_*ses 30

我认为您的问题是您没有使用正确的文件路径.

以下适用于我:

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 root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "temp/attachement.xml";
File file = new File(root, pathToMyAttachedFile);
if (!file.exists() || !file.canRead()) {
return;
}
Uri uri = Uri.fromFile(file);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));
Run Code Online (Sandbox Code Playgroud)

您还需要通过下面的清单文件授予用户权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)


div*_*nas 6

对于较新的设备,您将遇到 FileUriExposedException。以下是如何在 Kotlin 中避免这种情况。

val file = File(Environment.getExternalStorageDirectory(), "this")
val authority = context.packageName + ".provider"
val uri = FileProvider.getUriForFile(context, authority, file)
val emailIntent = createEmailIntent(uri)
startActivity(Intent.createChooser(emailIntent, "Send email..."))

private fun createEmailIntent(attachmentUri: Uri): Intent {
    val emailIntent = Intent(Intent.ACTION_SEND)
    emailIntent.type = "vnd.android.cursor.dir/email"
    val to = arrayOf("some@email.com")
    emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
    emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri)
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject")
    return emailIntent
}
Run Code Online (Sandbox Code Playgroud)