如何从我的Android应用程序发送电子邮件?

555

我正在开发一款安卓应用程序。我不知道如何从应用程序中发送电子邮件?


简单的ShareBuilder https://gist.github.com/gelldur/9c199654c91b13478979 - Gelldur
这个回答解决了你的问题吗?Android Studio mailto Intent doesn't show subject and mail body - Alex
建议的重复似乎更糟糕,被接受的答案有一个奇怪、不必要的意图过滤器。 - Ryan M
26个回答

1

试试这个:

String mailto = "mailto:bob@example.org" +
    "?cc=" + "alice@example.com" +
    "&subject=" + Uri.encode(subject) +
    "&body=" + Uri.encode(bodyText);

Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse(mailto));

try {
    startActivity(emailIntent);
} catch (ActivityNotFoundException e) {
    //TODO: Handle case where no email app is available
}

上述代码将打开用户喜爱的电子邮件客户端,并填充准备发送的电子邮件。

来源


1
以下代码适用于 Android 10 及更高版本的设备。它还设置了主题、正文和收件人(To)。
val uri = Uri.parse("mailto:$EMAIL")
                .buildUpon()
                .appendQueryParameter("subject", "App Feedback")
                .appendQueryParameter("body", "Body Text")
                .appendQueryParameter("to", EMAIL)
                .build()

            val emailIntent = Intent(Intent.ACTION_SENDTO, uri)

            startActivity(Intent.createChooser(emailIntent, "Select app"))

1

筛选“真正”的电子邮件应用程序仍然是今天的一个问题。正如许多人在上面提到的,现在其他应用程序也报告支持mime类型“message/rfc822”。因此,这种mime类型不再适合过滤真正的电子邮件应用程序。

如果您想发送简单文本邮件,只需使用适当的数据类型和ACTION_SENDTO意图操作即可:

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
Intent chooser = Intent.createChooser(intent, "Send Mail");
context.startActivity(chooser);

这将过滤所有可用的应用程序,以支持“mailto”协议,这更适合于发送电子邮件的目的。

但是,如果您想发送带有(多个)附件的邮件,则情况变得复杂。 ACTION_SENDTO操作不支持意图上的EXTRA_STREAM额外内容。如果您想使用它,必须使用ACTION_SEND_MULTIPLE操作,但它不能与数据类型Uri.parse("mailto:")一起使用。

目前我找到了一个解决方案,包括以下步骤:

  • 声明您的应用程序要查询设备上支持mailto协议的应用程序(对于Android 11之后的所有应用程序都很重要)
  • 实际查询支持mailto协议的所有应用程序
  • 针对每个支持的应用程序:构建您实际想要启动的意图,瞄准该单个应用程序
  • 构建应用程序选择器并启动它

以下是代码示例:

将此添加到 AndroidManifest 中:

<queries>
    <intent>
        <action android:name="android.intent.action.SENDTO" />
        <data android:scheme="mailto" />
    </intent>
</queries>

这是Java代码:

/* Query all Apps that support the 'mailto' protocol */
PackageManager pm = context.getPackageManager();
Intent emailCheckerIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
List<ResolveInfo> emailApps = pm.queryIntentActivities(emailCheckerIntent, PackageManager.MATCH_DEFAULT_ONLY);

/* For each supporting App: Build an intent with the desired values */
List<Intent> intentList = new ArrayList<>();
for (ResolveInfo resolveInfo : emailApps) {
    String packageName = resolveInfo.activityInfo.packageName;
    Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.setPackage(packageName);
    intent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name));
    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, text);
    intent.putExtra(Intent.EXTRA_STREAM, attachmentUris);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //IMPORTANT to give the E-Mail App access to your attached files
                
    intentList.add(intent);
}

/* Create a chooser consisting of the queried apps only */
Intent chooser = Intent.createChooser(intentList.remove(intentList.size() - 1), "Send Mail");
Intent[] extraIntents = intentList.toArray(new Intent[0]);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
context.startActivity(chooser);

注意:如果itentList只有一个项目,Android将自动跳过选择器并自动运行唯一的应用程序。


1
/**
 * Will start the chosen Email app
 *
 * @param context    current component context.
 * @param emails     Emails you would like to send to.
 * @param subject    The subject that will be used in the Email app.
 * @param forceGmail True - if you want to open Gmail app, False otherwise. If the Gmail
 *                   app is not installed on this device a chooser will be shown.
 */
public static void sendEmail(Context context, String[] emails, String subject, boolean forceGmail) {

    Intent i = new Intent(Intent.ACTION_SENDTO);
    i.setData(Uri.parse("mailto:"));
    i.putExtra(Intent.EXTRA_EMAIL, emails);
    i.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (forceGmail && isPackageInstalled(context, "com.google.android.gm")) {
        i.setPackage("com.google.android.gm");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    } else {
        try {
            context.startActivity(Intent.createChooser(i, "Send mail..."));
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "No email app is installed on your device...", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 * Check if the given app is installed on this devuice.
 *
 * @param context     current component context.
 * @param packageName The package name you would like to check.
 * @return True if this package exist, otherwise False.
 */
public static boolean isPackageInstalled(@NonNull Context context, @NonNull String packageName) {
    PackageManager pm = context.getPackageManager();
    if (pm != null) {
        try {
            pm.getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    return false;
}

1

只显示电子邮件客户端的 Kotlin 版本(不包括联系人等):

    with(Intent(Intent.ACTION_SEND)) {
        type = "message/rfc822"
        data = Uri.parse("mailto:")
        putExtra(Intent.EXTRA_EMAIL, arrayOf("user@example.com"))
        putExtra(Intent.EXTRA_SUBJECT,"YOUR SUBJECT")
        putExtra(Intent.EXTRA_TEXT, "YOUR BODY")
        try {
            startActivity(Intent.createChooser(this, "Send Email with"))
        } catch (ex: ActivityNotFoundException) {
            // No email clients found, might show Toast here
        }
    }

0
import androidx.core.app.ShareCompat
import androidx.core.content.IntentCompat

ShareCompat.IntentBuilder(this)
                .setType("message/rfc822")
                .setEmailTo(arrayOf(email))
                .setStream(uri)
                .setSubject(subject)
                .setText(message + emailMessage)
                .startChooser()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接