首页 文章

如何从我的Android应用程序发送电子邮件?

提问于
浏览
476

我正在为Android编写应用程序 . 我该如何发送电子邮件?

18 回答

  • 3

    最好(也是最简单)的方法是使用 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();
    }
    

    否则你将不得不编写自己的客户端 .

  • 12

    使用 .setType("message/rfc822") 或选择器将显示支持发送意图的所有(许多)应用程序 .

  • 77

    很久以前我一直在使用它,看起来不错,没有非电子邮件应用程序出现 . 发送电子邮件意图的另一种方法:

    Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of email");
    intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
    intent.setData(Uri.parse("mailto:default@recipient.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);
    
  • 188

    我正在使用当前接受的答案中的某些内容,以便发送带有附加二进制错误日志文件的电子邮件 . GMail和K-9发送它很好,它也可以在我的邮件服务器上正常运行 . 唯一的问题是我选择Thunderbird的邮件客户端在打开/保存附加的日志文件时遇到了麻烦 . 事实上,它根本没有保存文件,没有抱怨 .

    我看了一下这些邮件的源代码,发现日志文件附件(可以理解)是mime类型 message/rfc822 . 当然,附件不是附加的电子邮件 . 但Thunderbird无法优雅地应对这一微小错误 . 所以这有点令人失望 .

    经过一些研究和实验,我想出了以下解决方案:

    public Intent createEmailOnlyChooserIntent(Intent source,
            CharSequence chooserTitle) {
            Stack<Intent> intents = new Stack<Intent>();
            Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
                    "info@domain.com", null));
            List<ResolveInfo> activities = getPackageManager()
                    .queryIntentActivities(i, 0);
    
            for(ResolveInfo ri : activities) {
                Intent target = new Intent(source);
                target.setPackage(ri.activityInfo.packageName);
                intents.add(target);
            }
    
            if(!intents.isEmpty()) {
                Intent chooserIntent = Intent.createChooser(intents.remove(0),
                        chooserTitle);
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                        intents.toArray(new Parcelable[intents.size()]));
    
                return chooserIntent;
            } else {
                return Intent.createChooser(source, chooserTitle);
            }
        }
    

    它可以使用如下:

    Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("*/*");
            i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(crashLogFile));
            i.putExtra(Intent.EXTRA_EMAIL, new String[] {
                ANDROID_SUPPORT_EMAIL
            });
            i.putExtra(Intent.EXTRA_SUBJECT, "Crash report");
            i.putExtra(Intent.EXTRA_TEXT, "Some crash report details");
    
            startActivity(createEmailOnlyChooserIntent(i, "Send via email"));
    

    如您所见,createEmailOnlyChooserIntent方法可以很容易地使用正确的意图和正确的mime类型 .

    然后,它会查看响应ACTION_SENDTO mailto 协议意图(仅限电子邮件应用程序)的可用活动列表,并根据该活动列表和具有正确mime类型的原始ACTION_SEND意图构建选择器 .

    另一个优点是Skype不再被列出(这恰好响应了rfc822的mime类型) .

  • 49

    JUST LET EMAIL APPS 来解决您的意图,您需要将ACTION_SENDTO指定为Action并将mailto指定为Data .

    private void sendEmail(){
    
        Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
        emailIntent.setData(Uri.parse("mailto:" + "recipient@example.com")); 
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My email's subject");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "My email's body");
    
        try {
            startActivity(Intent.createChooser(emailIntent, "Send email using..."));
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(Activity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
        }
    
    }
    
  • 2

    使用 .setType("message/rfc822")ACTION_SEND 的策略似乎也匹配不是电子邮件客户端的应用程序,例如Android Beam和蓝牙 .

    使用 ACTION_SENDTOmailto: URI似乎完美无缺,并且is recommended in the developer documentation . 但是,如果您在官方模拟器上执行此操作并且没有't any email accounts set up (or there aren' t任何邮件客户端),则会出现以下错误:

    不支持的操作当前不支持该操作 .

    如下所示:

    Unsupported action: That action is not currently supported.

    事实证明,模拟器将意图解析为名为com.android.fallback.Fallback的活动,该活动显示上述消息 . Apparently this is by design.

    如果您希望您的应用程序绕过这个,以便它也可以在官方模拟器上正常工作,您可以在尝试发送电子邮件之前检查它:

    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 <johnsmith@yourdomain.com>" })
            .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();
    }
    

    the developer documentation中查找更多信息 .

  • 33

    我用android文档解释的简单的代码行解决了这个问题 .

    https://developer.android.com/guide/components/intents-common.html#Email

    最重要的是旗帜:它是 ACTION_SENDTO ,而不是 ACTION_SEND

    另一个重要的是

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

    顺便说一句,如果你发送一个空的 Extra ,那么 if() 最终会赢得't work and the app won' t启动电子邮件客户端 .

    根据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);
        }
    }
    
  • 18

    发送电子邮件可以使用Intents完成,无需配置 . 但随后它将需要用户交互,布局将受到一定限制 .

    无需用户交互即可构建和发送更复杂的电子邮件,这需要构建自己的客户端 . 第一件事是Sun Java API for email不可用 . 我已成功利用Apache Mime4j库来构建电子邮件 . 全部基于nilvec的文档 .

  • 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 :"));
    
            }
        });
    }
    
  • 16

    我在我的应用程序中使用以下代码 . 这会准确显示电子邮件客户端应用,例如Gmail .

    Intent contactIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.email_to), null));
        contactIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject));
        startActivity(Intent.createChooser(contactIntent, getString(R.string.email_chooser)));
    
  • 2

    这是示例工作代码,它在Android设备中打开 mail application 并在撰写邮件中自动填充 To addressSubject .

    protected void sendEmail() {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:feedback@gmail.com"));
        intent.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }
    }
    
  • 0

    其他解决办法可以

    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应用程序 .

  • 1

    用它来发送电子邮件......

    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

    此功能首先直接用于发送电子邮件的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);
            }
        }
    }
    
  • 0

    这将仅向您显示电子邮件客户端(以及出于某种未知原因的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();
        }
    }
    
  • 3

    这就是我做到的 . 很好,很简单 .

    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);
    
  • 912

    这种方法适合我 . 它会打开Gmail应用程序(如果已安装)并设置mailto .

    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);
    }
    
  • 3

    I used this code to send mail by launching default mail app compose section directly.

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

相关问题