我正在开发一个应用程序在Android。我不知道如何从应用程序发送电子邮件?
最好的(也是最简单的)方法是使用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();
}
否则你就得自己写客户端了。
发送电子邮件可以用intent完成,不需要配置。但这样就需要用户交互,布局也会受到一些限制。
在没有用户交互的情况下构建和发送更复杂的电子邮件需要构建自己的客户端。第一件事是用于电子邮件的Sun Java API不可用。我曾经成功地利用Apache Mime4j库来构建电子邮件。都是基于nilvec的文件。
我很久以前就一直在用这个,看起来不错,没有非电子邮件应用程序显示。这是发送电子邮件意图的另一种方式:
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@example.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);
简单,试试这个
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 :"));
}
});
}
为了发送带有附加二进制错误日志文件的电子邮件,我使用了当前接受的答案。GMail和K-9发送得很好,在我的邮件服务器上也很好。唯一的问题是我选择的邮件客户端Thunderbird,它在打开/保存附加的日志文件时遇到了麻烦。事实上,它根本没有保存文件,没有抱怨。
我查看了其中一封邮件的源代码,注意到日志文件附件具有mime类型消息/rfc822(这是可以理解的)。当然这个附件不是附件邮件。但雷鸟无法优雅地处理这个微小的错误。所以这有点令人沮丧。
经过一些研究和实验,我想出了以下解决方案:
public Intent createEmailOnlyChooserIntent(Intent source,
CharSequence chooserTitle) {
Stack<Intent> intents = new Stack<Intent>();
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
"info@example.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邮件协议意图(仅是电子邮件应用程序)的可用活动列表,并基于该活动列表和具有正确mime类型的原始ACTION_SEND意图构造一个选择器。
另一个优点是Skype不再被列出(这恰好响应rfc822 mime类型)。
为了让电子邮件应用程序来解决你的意图,你需要指定ACTION_SENDTO作为动作和mailto作为数据。
private void sendEmail(){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:" + "recipient@example.com")); // You can use "mailto:" if you don't know the address beforehand.
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();
}
}
使用. settype ("message/rfc822")或ACTION_SEND的策略似乎也适用于非电子邮件客户端的应用程序,如Android Beam和蓝牙。
使用ACTION_SENDTO和mailto: 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 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();
}
在开发人员文档中找到更多信息。
解决方案很简单:android文档解释了这一点。
(https://developer.android.com/guide/components/intents-common.html邮件)
最重要的是标志:它是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 this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
其他解决方案可以是
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应用程序。
我是这么做的。很好很简单。
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);
我在我的应用程序中使用下面的代码。这显示准确的电子邮件客户端应用程序,如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)));
使用这个发送电子邮件…
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'
这将只显示您的电子邮件客户端(以及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();
}
}
这个函数首先直接意图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);
}
}
}
这个方法对我有用。它打开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);
}
下面是在android设备中打开邮件应用程序并在编写邮件时自动填充To address和Subject的示例工作代码。
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);
}
}
我使用这段代码通过直接启动默认的邮件应用程序撰写部分来发送邮件。
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();
}
/**
* 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;
}
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..."));
试试这个:
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
}
上面的代码将打开用户最喜欢的电子邮件客户端预填充的电子邮件准备发送。
源
Kotlin版本,只显示电子邮件客户端(没有联系人等):
with(Intent(Intent.ACTION_SEND)) {
type = "message/rfc822"
data = Uri.parse("mailto:")
putExtra(Intent.EXTRA_EMAIL, arrayOf("user@example.com"))
putExtra(Intent.EXTRA_SUBJECT,"YOUR SUBJECT")
putExtra(Intent.EXTRA_TEXT, "YOUR BODY")
try {
startActivity(Intent.createChooser(this, "Send Email with"))
} catch (ex: ActivityNotFoundException) {
// No email clients found, might show Toast here
}
}
下面的代码可以在Android 10及更高的设备上运行。它还设置了主题、正文和收件人(To)。
val uri = Uri.parse("mailto:$EMAIL")
.buildUpon()
.appendQueryParameter("subject", "App Feedback")
.appendQueryParameter("body", "Body Text")
.appendQueryParameter("to", EMAIL)
.build()
val emailIntent = Intent(Intent.ACTION_SENDTO, uri)
startActivity(Intent.createChooser(emailIntent, "Select app"))
import androidx.core.app.ShareCompat
import androidx.core.content.IntentCompat
ShareCompat.IntentBuilder(this)
.setType("message/rfc822")
.setEmailTo(arrayOf(email))
.setStream(uri)
.setSubject(subject)
.setText(message + emailMessage)
.startChooser()
这是在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)
}
您还需要在清单中(在应用程序标记之外)指定处理电子邮件的应用程序的查询(mailto)。
<queries>
<intent>
<action android:name="android.intent.action.SENDTO" />
<data android:scheme="mailto" />
</intent>
</queries>
如果你需要在电子邮件正文中发送HTML文本,请将“电子邮件正文”替换为你的电子邮件字符串,就像这样(请注意HTML . fromhtml可能已经弃用了,这只是为了告诉你如何做)
Html.fromHtml(
StringBuilder().append("<b>Hello world</b>").toString()
)
筛选“真正的”电子邮件应用程序在今天仍然是一个问题。正如上面许多人提到的,现在其他应用程序也报告支持mime类型的“message/rfc822”。因此,这种mime类型不再适合用于真正的电子邮件应用程序的过滤。
如果你想发送一个简单的文本邮件,使用ACTION_SENDTO意图动作和适当的数据类型就足够了,如下所示:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
Intent chooser = Intent.createChooser(intent, "Send Mail");
context.startActivity(chooser);
这将过滤所有支持“mailto”协议的应用程序,这更适合发送电子邮件。
但不幸的是,如果你想发送带有(多个)附件的邮件,事情就变得复杂了。ACTION_SENDTO动作不支持EXTRA_STREAM额外的意图。如果你想使用它,你必须使用ACTION_SEND_MULTIPLE动作,它不能与数据类型Uri.parse("mailto:")一起工作。
目前我找到了一个解决方案,具体步骤如下:
声明你的应用程序想要查询设备上支持mailto协议的应用程序(对Android 11以来的所有应用程序都很重要) 实际上查询所有支持mailto协议的应用程序 对于每个支持应用:构建你真正想要启动的意图,针对那个单一的应用 构建App选择器并启动它
这是它在代码中的样子:
添加到AndroidManifest:
<queries>
<intent>
<action android:name="android.intent.action.SENDTO" />
<data android:scheme="mailto" />
</intent>
</queries>
这是Java代码:
/* Query all Apps that support the 'mailto' protocol */
PackageManager pm = context.getPackageManager();
Intent emailCheckerIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
List<ResolveInfo> emailApps = pm.queryIntentActivities(emailCheckerIntent, PackageManager.MATCH_DEFAULT_ONLY);
/* For each supporting App: Build an intent with the desired values */
List<Intent> intentList = new ArrayList<>();
for (ResolveInfo resolveInfo : emailApps) {
String packageName = resolveInfo.activityInfo.packageName;
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setPackage(packageName);
intent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name));
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.putExtra(Intent.EXTRA_STREAM, attachmentUris);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //IMPORTANT to give the E-Mail App access to your attached files
intentList.add(intent);
}
/* Create a chooser consisting of the queried apps only */
Intent chooser = Intent.createChooser(intentList.remove(intentList.size() - 1), "Send Mail");
Intent[] extraIntents = intentList.toArray(new Intent[0]);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
context.startActivity(chooser);
注意:如果itentList只有一个项目,Android会自动跳过选择器并自动运行唯一的应用程序。
推荐文章
- 如何在Jenkins中设置发件人地址?
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 什么是最好的Java电子邮件地址验证方法?
- 如何在Android工作室的外部库中添加一个jar ?