我正在为Android编写应用程序。我该如何发送电子邮件?
答案 0 :(得分:937)
最好(也是最简单)的方法是使用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();
}
否则你必须自己编写客户端。
答案 1 :(得分:190)
使用.setType("message/rfc822")
或选择器将显示支持发送意图的所有(许多)应用程序。
答案 2 :(得分:78)
我很久以前一直在使用它,看起来不错,没有非电子邮件应用程序出现。另一种发送电子邮件意图的方式:
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);
答案 3 :(得分:49)
我正在使用当前接受的答案中的某些内容,以便发送带有附加二进制错误日志文件的电子邮件。 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类型)。
答案 4 :(得分:34)
要 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();
}
}
答案 5 :(得分:19)
我用简单的代码行解决了这个问题,正如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
操作并添加“ { {1}} “数据方案。例如:
mailto:
答案 6 :(得分:18)
使用.setType("message/rfc822")
或ACTION_SEND
的策略似乎也匹配非电子邮件客户端的应用,例如 Android Beam 和 Bluetooth
使用ACTION_SENDTO
和mailto:
URI似乎完美无缺,is recommended in the developer documentation。但是,如果您在官方模拟器上执行此操作并且没有设置任何电子邮件帐户(或者没有任何邮件客户端),则会出现以下错误:
不支持的操作
目前不支持该操作。
如下图所示:
事实证明,模拟器将意图解析为名为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中查找更多信息。
答案 7 :(得分:12)
发送电子邮件可以使用Intents完成,无需配置。但随后它将需要用户交互,布局将受到一定限制。
在没有用户交互的情况下构建和发送更复杂的电子邮件需要构建自己的客户端。第一件事是Sun Java API for email不可用。我已成功利用Apache Mime4j库来构建电子邮件。全部基于nilvec的文档。
答案 8 :(得分:3)
我在我的应用中使用以下代码。这会准确显示电子邮件客户端应用,例如Gmail。
right-click on project > Team > Share
答案 9 :(得分:3)
以下示例工作代码在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);
}
}
答案 10 :(得分:3)
简单试试这个
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 :"));
}
});
}
答案 11 :(得分:2)
其他解决方案可以
for(int x=0; x < TCPSourceIP.size(); x++){
jTextArea1.append(x+1+")IP " + TCPSourceIP.get(x) +" is sending packet using TCP Port "+
TCPSrcPort.get(x) + " to IP " + TCPDestIP.get(x) + "(" + TCPDestPort.get(x) +")" +
" which is non-standard port\n");
假设大多数Android设备已经安装了GMail应用程序。
答案 12 :(得分:2)
用于发送电子邮件......
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'
答案 13 :(得分:2)
这将仅向您显示电子邮件客户端(以及出于某种未知原因的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();
}
}
答案 14 :(得分:2)
This function first direct intent gmail for sending email, if gmail is not found then promote intent chooser. I used this function in many commercial app and it's working fine. Hope it will help you:
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);
}
}
}
答案 15 :(得分:1)
这就是我做的。好又简单。
function AdditivePersistence(num) {
let str = num.toString; //number into string
let arr = str.split(""); //string into array
// adds numbers in array, then repeats until left with single digit
let count = 0;
while(arr.length > 1) {
arr.reduce(function(a,b){ return Number(a) + Number(b) });
count++;
}
return count;
};
答案 16 :(得分:1)
尝试一下:
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
}
上面的代码将打开用户喜欢的电子邮件客户端,该客户端预填充了准备发送的电子邮件。
答案 17 :(得分:1)
仅显示电子邮件客户端(无联系人等)的 Kotlin 版本:
with(Intent(Intent.ACTION_SEND)) {
type = "message/rfc822"
data = Uri.parse("mailto:")
putExtra(Intent.EXTRA_EMAIL, arrayOf("example@mail.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
}
}
答案 18 :(得分:0)
这种方法适合我。它会打开Gmail应用程序(如果已安装)并设置mailto。
private static int doSth(AtomicInteger counter) {
try {
Random r = new Random();
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int counterValue = counter.incrementAndGet();
out.println(">>doSth2: " + Thread.currentThread().getName() + " value: " + counterValue);
return counterValue;
}
答案 19 :(得分:0)
我使用此代码通过直接启动默认邮件应用撰写部分来发送邮件。
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();
}
答案 20 :(得分:0)
{{1}}
答案 21 :(得分:0)
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**
答案 22 :(得分:0)
以下代码适用于 Android 10 及更高版本的设备。它还设置主题、正文和收件人(收件人)。
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"))