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


当前回答

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

其他回答

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

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:

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT   , "body of email");
try {
    startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

否则你就得自己写客户端了。

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

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 emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("plain/text");
emailIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"someone@gmail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Yo");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi");
startActivity(emailIntent);

假设大多数android设备已经安装了GMail应用程序。