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


#1楼

简单尝试这个

 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() {@Overridepublic 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 onlyemail.setType("message/rfc822");startActivity(Intent.createChooser(email, "Choose an Email client :"));}});
}

#2楼

我正在按照当前接受的答案使用某些东西,以便发送带有附加二进制错误日志文件的电子邮件。 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协议意图的可用活动列表(仅电子邮件应用程序),并基于该活动列表和原始ACTION_SEND意图(具有正确的mime类型)构造选择器。

另一个优点是Skype不再列出(这恰好是对rfc822 MIME类型的响应)。


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

否则,您将必须编写自己的客户端。


#4楼

可以使用Intents发送电子邮件,而无需进行配置。 但是,这将需要用户交互,并且布局会受到一些限制。

在没有用户交互的情况下构建和发送更复杂的电子邮件需要构建自己的客户端。 第一件事是电子邮件的Sun Java API不可用。 我已经成功利用Apache Mime4j库构建电子邮件。 全部基于nilvec上的文档。


#5楼

要仅删除电子邮件应用程序即可解决您的意图,您需要将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();}}

#6楼

使用.setType("message/rfc822")ACTION_SEND似乎也可以匹配非电子邮件客户端的应用程序,例如Android BeamBluetooth

使用ACTION_SENDTOmailto: URI似乎可以正常工作,并且在开发人员文档中建议使用 。 但是,如果您在官方模拟器上执行此操作,并且没有设置任何电子邮件帐户(或没有任何邮件客户端),则会出现以下错误:

不支持的动作

目前不支持该操作。

如下所示:

事实证明,仿真器将意图解析为名为com.android.fallback.Fallback的活动,该活动显示上述消息。 显然,这是设计使然。

如果您希望您的应用程序绕过此问题,以便它也可以在官方模拟器上正常运行,则可以在尝试发送电子邮件之前先进行检查:

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

在开发人员文档中查找更多信息。


#7楼

如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()将不起作用,并且该应用程序将不会启动电子邮件客户端。

根据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 thisintent.putExtra(Intent.EXTRA_EMAIL, addresses);intent.putExtra(Intent.EXTRA_SUBJECT, subject);if (intent.resolveActivity(getPackageManager()) != null) {startActivity(intent);}
}

#8楼

其他解决方案可以是

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应用。


#9楼

这就是我做的。 漂亮又简单。

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

#10楼

我在应用程序中使用以下代码。 这将准确显示电子邮件客户端应用程序,例如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)));

#11楼

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

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'

#12楼

这只会向您显示电子邮件客户端(以及某些未知原因的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();}
}

#13楼

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


#14楼

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

#15楼

这种方法对我有用。 它将打开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);
}

#16楼

这是示例工作代码,该代码在android设备中打开邮件应用程序 ,并自动在撰写邮件中填充“ 收件人”地址和“ 主题 ”。

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

#17楼

我使用此代码通过直接启动默认的邮件应用程序撰写部分来发送邮件。

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

#18楼

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

#19楼

 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, "Write your Pubg user name or Phone Number");startActivity(Intent.createChooser(emailIntent, "Send email..."));**strong text**

#20楼

尝试这个:

String mailto = "mailto:bob@example.org" +"?cc=" + "alice@example.com" +"&subject=" + Uri.encode(subject) +"&body=" + Uri.encode(bodyText);Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse(mailto));try {startActivity(emailIntent);
} catch (ActivityNotFoundException e) {//TODO: Handle case where no email app is available
}

上面的代码将打开用户喜欢的电子邮件客户端,该客户端预填充了准备发送的电子邮件。

资源


#21楼

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

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@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);

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

  1. android java广播,[原]Android应用程序发送广播(sendBroadcast)的过程分析

    前面我们分析了Android应用程序注册广播接收器的过程,这个过程只完成了万里长征的第一步,接下来它还要等待ActivityManagerService将广播分发过来.ActivityManagerS ...

  2. (邮件/用户)代理协议简介Socket程序发送电子邮件

    目录 邮件收发 基本流程 具体过程 协议简介 SMTP POP3 IMAP MIME 在.NET中如何实现 常用的邮件服务器地址: 126邮箱 163邮箱 yahoo邮箱 Sohu邮箱 Gmail邮箱 ...

  3. Android实现快速发送电子邮件

    最近有朋友有需求是通过apk发送邮件,我心想这怎么可以实现?然后就研究了一番,最后得出结论是可行的! 确实可以自己的手机上定义主题和内容或者附件,然后发送给对应的邮箱!详细步骤倾听我一一道来 我们以A ...

  4. java发送hotmail邮件_如何使用Gmail、Yahoo或Hotmail通过Java应用程序发送电子邮件?...

    首先下载JavaMail API并确保相关的JAR文件在您的类路径中. 下面是一个使用Gmail的完整示例.import java.util.*;import javax.mail.*;import  ...

  5. Android应用程序消息处理机制(Looper、Handler)分析(1)

    Android应用程序是通过消息来驱动的,系统为每一个应用程序维护一个消息队例,应用程序的主线程不断地从这个消息队例中获取消息(Looper),然后对这些消息进行处理(Handler),这样就实现了通 ...

  6. Android 应用程序消息处理机制(Looper、Handler)分析

    Android应用程序是通过消息来驱动的,系统为每一个应用程序维护一个消息队例,应用程序的主线程不断地从这个消息队例中获取消息(Looper),然后对这些消息进行处理(Handler),这样就实现了通 ...

  7. Android应用程序消息处理机制(Looper、Handler)分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6817933 Android应用程序是通过消息来 ...

  8. android发送电子邮件,Android发送电子邮件

    电子邮件 是通过电子方式从一个系统用户通过网络分发给一个或多个接收者的消息. 在开始电子邮件活动之前,您必须知道具有意图的电子邮件功能,Intent将数据从一个组件传送到应用程序中或应用程序外部的另一 ...

  9. android studio发邮件功能,Android发送电子邮件

    电子邮件是通过电子方式从一个系统用户通过网络分发给一个或多个收件人的邮件. 在开始电子邮件活动之前,您必须意图了解电子邮件功能,Intent在应用程序或应用程序外部将数据从一个组件传输到另一个组件. ...

最新文章

  1. Android USB Gadget复合设备驱动(打印机)测试方法
  2. 【Alertmanager】腾讯企业邮箱配置
  3. jQuery.merge与concat的区别
  4. Python的regex模块——更强大的正则表达式引擎
  5. java的圆周率_java学习日记,圆周率的打印
  6. smem – Linux 内存监视软件
  7. c#和c++的opencv位图数据参数互换问题解决方法
  8. 数据结构——最小生成树之prime算法(与最短路径之迪杰斯特拉算法很像)
  9. c语言输入字符时控制符%c前加空格的原因解释
  10. 不续签合同,凭什么要求别人紧急加班
  11. 第11章 支撑向量机 SVM 学习笔记 下 高斯核函数RBF
  12. nginx Linux 环境下安装
  13. 一句话教你认出世界名画作者!
  14. 09、Non-Black-Box ZK(Barak‘s protocol)--Alon Rosen
  15. usemvc永远不会被使用_你永远不会离开
  16. yutons_sug搜索框提示插件||输入框提示插件
  17. 移动端手指滑动的距离
  18. 会场安排问题(活动场次而不是会场场次)
  19. Java实现输出水仙花(易懂)
  20. Webstorm干货(开发效率快到飞起!!!)

热门文章

  1. 自动化Build的方法如下所示
  2. adb logcat read: unexpected EOF!
  3. Android Launcher3(二) -- Drag拖动实现
  4. Kotlin返回值Unit、Nothing与Any
  5. Android中ActivityLifecycleCallbacks的使用
  6. Kotlin特色之object、let、with、run、apply、also函数的使用
  7. 手机编程micropython_MicroPython可视化拼插编辑器:让硬件编程更智能!
  8. (0052)iOS开发之沙盒(sandbox)机制和文件操作(二)
  9. linux的零碎知识
  10. 从源码角度入手实现RecyclerView的Item点击事件