如何从我的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个回答

5
这将只显示电子邮件客户端(以及由于某些未知原因的PayPal)。
 public void composeEmail() {

    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:"));
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"hi@example.com"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    intent.putExtra(Intent.EXTRA_TEXT, "Body");
    try {
        startActivity(Intent.createChooser(intent, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
}

1
不错的解决方案!它避免了许多不适当的应用程序(主要用于“分享”)。不要在这里添加 intent.type =“message/rfc822”; intent.type =“text/html”;,因为它会导致异常。 - CoolMind

4
这是我的做法。简单易懂。
String emailUrl = "mailto:email@example.com?subject=Subject Text&body=Body Text";
        Intent request = new Intent(Intent.ACTION_VIEW);
        request.setData(Uri.parse(emailUrl));
        startActivity(request);

4
我使用了这段代码直接启动默认的邮件应用程序,以发送邮件。
    Intent i = new Intent(Intent.ACTION_SENDTO);
    i.setType("message/rfc822"); 
    i.setData(Uri.parse("mailto:"));
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"test@gmail.com"});
    i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    i.putExtra(Intent.EXTRA_TEXT   , "body of email");
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

3

这是在Android上发送电子邮件最简洁的方法。

 val intent = Intent(Intent.ACTION_SENDTO).apply {
    data = Uri.parse("mailto:")
    putExtra(Intent.EXTRA_EMAIL, arrayOf("email@example.com"))
    putExtra(Intent.EXTRA_SUBJECT, "Subject")
    putExtra(Intent.EXTRA_TEXT, "Email body")
}
if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
}

你还需要在你的清单文件(manifest)中(位于应用标签之外)指定处理电子邮件(mailto)的应用程序的查询。
<queries>
    <intent>
        <action android:name="android.intent.action.SENDTO" />
        <data android:scheme="mailto" />
    </intent>
</queries>

如果您需要在电子邮件正文中发送HTML文本,请将"Email body"替换为您的电子邮件字符串,就像这样(请注意,Html.fromHtml可能已废弃,这只是为了向您展示如何操作)。
Html.fromHtml(
    StringBuilder().append("<b>Hello world</b>").toString()
)

3

此函数首先直接使用 Gmail 发送电子邮件,如果找不到 Gmail,则会提示选择器。我在许多商业应用程序中使用了此功能,它运行良好。希望能对您有所帮助:

public static void sentEmail(Context mContext, String[] addresses, String subject, String body) {

    try {
        Intent sendIntentGmail = new Intent(Intent.ACTION_VIEW);
        sendIntentGmail.setType("plain/text");
        sendIntentGmail.setData(Uri.parse(TextUtils.join(",", addresses)));
        sendIntentGmail.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
        sendIntentGmail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentGmail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentGmail.putExtra(Intent.EXTRA_TEXT, body);
        mContext.startActivity(sendIntentGmail);
    } catch (Exception e) {
        //When Gmail App is not installed or disable
        Intent sendIntentIfGmailFail = new Intent(Intent.ACTION_SEND);
        sendIntentIfGmailFail.setType("*/*");
        sendIntentIfGmailFail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_TEXT, body);
        if (sendIntentIfGmailFail.resolveActivity(mContext.getPackageManager()) != null) {
            mContext.startActivity(sendIntentIfGmailFail);
        }
    }
}

1
非常感谢。救了我的命。 - androCoder-BD

2

使用此功能发送电子邮件...

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'

2
另一种解决方案可以是:
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);

假设大多数安卓设备已经预装了Gmail应用。


@PedroVarela 我们可以随时检查活动未找到异常。 - silentsudo
1
是的,我们可以。但你的解决方案不正确。Android文档清楚地说明了您需要做什么才能在意图选择器中仅显示邮件应用程序。您写道“假设大多数Android设备已经安装了Gmail应用程序”;如果它是一个rooted设备,并且用户删除了Gmail客户端呢?假设您正在创建自己的电子邮件应用程序?如果用户要发送电子邮件,您的应用程序将不会出现在列表中。如果gmail更改包名称会发生什么?您会更新您的应用程序吗? - Pedro Varela

2

尝试这个简单的方法

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonSend = (Button) findViewById(R.id.buttonSend);
    textTo = (EditText) findViewById(R.id.editTextTo);
    textSubject = (EditText) findViewById(R.id.editTextSubject);
    textMessage = (EditText) findViewById(R.id.editTextMessage);

    buttonSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            String to = textTo.getText().toString();
            String subject = textSubject.getText().toString();
            String message = textMessage.getText().toString();

            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
            // email.putExtra(Intent.EXTRA_CC, new String[]{ to});
            // email.putExtra(Intent.EXTRA_BCC, new String[]{to});
            email.putExtra(Intent.EXTRA_SUBJECT, subject);
            email.putExtra(Intent.EXTRA_TEXT, message);

            // need this to prompts email client only
            email.setType("message/rfc822");

            startActivity(Intent.createChooser(email, "Choose an Email client :"));

        }
    });
}

3
这有什么比你发布这篇文章时已经存在的答案更好吗?它看起来只是已接受答案的复制并以一个活动的形式呈现。 - Sam

2
 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..."));

1
这个方法对我很有用。它可以打开 Gmail 应用程序(如果已安装)并设置邮件地址。
public void openGmail(Activity activity) {
    Intent emailIntent = new Intent(Intent.ACTION_VIEW);
    emailIntent.setType("text/plain");
    emailIntent.setType("message/rfc822");
    emailIntent.setData(Uri.parse("mailto:"+activity.getString(R.string.mail_to)));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.app_name) + " - info ");
    final PackageManager pm = activity.getPackageManager();
    final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
    ResolveInfo best = null;
    for (final ResolveInfo info : matches)
        if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
            best = info;
    if (best != null)
        emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
    activity.startActivity(emailIntent);
}

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