How to send emails from my Android application?

前端 未结 21 2711
春和景丽
春和景丽 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 01:06

    /**
     * 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;
    }
    

提交回复
热议问题