我正在开发一个应用程序在Android。我不知道如何从应用程序发送电子邮件?


当前回答

 Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
            "mailto","ebgsoldier@gmail.com", null));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Forgot Password");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "this is a text ");
    startActivity(Intent.createChooser(emailIntent, "Send email..."));

其他回答

解决方案很简单:android文档解释了这一点。

(https://developer.android.com/guide/components/intents-common.html邮件)

最重要的是标志:它是ACTION_SENDTO,而不是ACTION_SEND

另一条重要的线是

intent.setData(Uri.parse("mailto:")); ***// only email apps should handle this***

顺便说一下,如果你发送一个空的Extra,末尾的if()将不起作用,应用程序将无法启动电子邮件客户端。

根据Android文档。如果你想确保你的意图只被电子邮件应用程序处理(而不是其他短信或社交应用程序),那么使用ACTION_SENDTO动作并包括“mailto:”数据方案。例如:

public void composeEmail(String[] addresses, String subject) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

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
        }
    }

我很久以前就一直在用这个,看起来不错,没有非电子邮件应用程序显示。这是发送电子邮件意图的另一种方式:

Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of email");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:default@example.com")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);

发送电子邮件可以用intent完成,不需要配置。但这样就需要用户交互,布局也会受到一些限制。

在没有用户交互的情况下构建和发送更复杂的电子邮件需要构建自己的客户端。第一件事是用于电子邮件的Sun Java API不可用。我曾经成功地利用Apache Mime4j库来构建电子邮件。都是基于nilvec的文件。

使用这个发送电子邮件…

boolean success = EmailIntentBuilder.from(activity)
    .to("support@example.org")
    .cc("developer@example.org")
    .subject("Error report")
    .body(buildErrorReport())
    .start();

使用build gradle:

compile 'de.cketti.mailto:email-intent-builder:1.0.0'