How to send emails from my Android application?

前端 未结 21 2743
春和景丽
春和景丽 2020-11-22 00:38

I am developing an application in Android. I don\'t know how to send an email from the application?

21条回答
  •  庸人自扰
    2020-11-22 00:58

    The strategy of using .setType("message/rfc822") or ACTION_SEND seems to also match apps that aren't email clients, such as Android Beam and Bluetooth.

    Using ACTION_SENDTO and a mailto: URI seems to work perfectly, and is recommended in the developer documentation. However, if you do this on the official emulators and there aren't any email accounts set up (or there aren't any mail clients), you get the following error:

    Unsupported action

    That action is not currently supported.

    As shown below:

    Unsupported action: That action is not currently supported.

    It turns out that the emulators resolve the intent to an activity called com.android.fallback.Fallback, which displays the above message. Apparently this is by design.

    If you want your app to circumvent this so it also works correctly on the official emulators, you can check for it before trying to send the email:

    private void sendEmail() {
        Intent intent = new Intent(Intent.ACTION_SENDTO)
            .setData(new Uri.Builder().scheme("mailto").build())
            .putExtra(Intent.EXTRA_EMAIL, new String[]{ "John Smith " })
            .putExtra(Intent.EXTRA_SUBJECT, "Email subject")
            .putExtra(Intent.EXTRA_TEXT, "Email body")
        ;
    
        ComponentName emailApp = intent.resolveActivity(getPackageManager());
        ComponentName unsupportedAction = ComponentName.unflattenFromString("com.android.fallback/.Fallback");
        if (emailApp != null && !emailApp.equals(unsupportedAction))
            try {
                // Needed to customise the chooser dialog title since it might default to "Share with"
                // Note that the chooser will still be skipped if only one app is matched
                Intent chooser = Intent.createChooser(intent, "Send email with");
                startActivity(chooser);
                return;
            }
            catch (ActivityNotFoundException ignored) {
            }
    
        Toast
            .makeText(this, "Couldn't find an email app and account", Toast.LENGTH_LONG)
            .show();
    }
    

    Find more info in the developer documentation.

提交回复
热议问题