I am trying to use an intent to send an email from my application but the To field of the email will not populate. If I add code to fill in the subject or text, they work fine. Just the To field will not populate.
I have also tried changing the type to "text/plain" and "text/html" but I get the same problem. Can anyone help please?
public void Email(){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822"); //set the email recipient
String recipient = getString(R.string.IntegralEmailAddress);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL , recipient);
//let the user choose what email client to use
startActivity(Intent.createChooser(emailIntent, "Send mail using...")); }
The email client I'm trying to use is Gmail
I think you are not passing recipient as array of string
it should be like
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] { "someone#gmail.com" });
In Kotlin - Android
fun sendMail(
activity: Activity,
emailIds: Array<String>,
subject: String,
textMessage: String
) {
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.type = "text/plain"
emailIntent.putExtra(Intent.EXTRA_EMAIL, emailIds)
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
emailIntent.putExtra(Intent.EXTRA_TEXT, textMessage)
emailIntent.setType("message/rfc822")
try {
activity.startActivity(
Intent.createChooser(
emailIntent,
"Send email using..."
)
)
} catch (ex: ActivityNotFoundException) {
Toast.makeText(
activity,
"No email clients installed.",
Toast.LENGTH_SHORT
).show()
}
}
Also you can use [ val emailIntent = Intent(Intent.ACTION_SENDTO) ] to invoke direct email
client
//argument of function
val subject = "subject of you email"
val eMailMessageTxt = "Add Message here"
val eMailId1 = "emailId1#gmail.com"
val eMailId2 = "emailId2#gmail.com"
val eMailIds: Array<String> = arrayOf(eMailId1,eMailId2)
//Calling function
sendMail(this, eMailIds, subject, eMailMessageTxt)
I hope this code snippet will help to kotlin developers.
Use this
public void Email(){
// use this to declare your 'recipient' string and get your email recipient from your string xml file
Resources res = getResources();
String recipient = getString(R.string.IntegralEmailAddress);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822"); //set the email recipient
emailIntent.putExtra(Intent.EXTRA_EMAIL, recipient);
//let the user choose what email client to use
startActivity(Intent.createChooser(emailIntent, "Send mail using..."));
``}
This will work :)
This is what android documentation says about Intent.Extra_Email
-A string array of all "To" recipient email addresses.
So you should feed string properly
You can read more over here
http://developer.android.com/guide/components/intents-common.html#Email
and here http://developer.android.com/guide/topics/resources/string-resource.html Or use the ACTION_SENDTO action and include the "mailto:" data scheme. For example:
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);
}
Couple of things:
1 - You need to set the action constant variable as ACTION_SENDTO. Intent intentEmail = new Intent(Intent.ACTION_SENDTO);
2 - If you want it to be opened by only the mail then use the setData() method: intentEmail.setData(Uri.parse("mailto:")); Otherwise it will ask you to open it as text, image, audio file by other apps present on your device.
3 - You need to pass the email ID string as an array object and not just as a string. String is: "name#email.com". Array Object of the string is: new String[] {"email1", "email2", "more_email"}.
intentEmail.putExtra(Intent.EXTRA_EMAIL, new String[] {"email#overflow.com", "abcd#stack.com"});
private void callSendMeMail() {
Intent Email = new Intent(Intent.ACTION_SEND);
Email.setType("text/email");
Email.putExtra(Intent.EXTRA_EMAIL, new String[] { "me#gmail.com" });
Email.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
startActivity(Intent.createChooser(Email, "Send mail to Developer:"));
}
Made me waste so much time! Thanks to the accepted answer!
I'll add some Kotlin code with a couple of handy extension functions
fun Activity.hasEmailClient(): Boolean =
emailIntent("someAddress", "someSubject", "someText")
.resolveActivity(packageManager) != null
fun Activity.openEmailClient(address: String, subject: String, text: String) {
startActivity(emailIntent(address, subject, text))
}
private fun emailIntent(address: String, subject: String, text: String): Intent =
Intent(Intent.ACTION_SENDTO).apply {
type = "text/plain"
data = Uri.parse("mailto:")
putExtra(Intent.EXTRA_EMAIL, arrayOf(address))
putExtra(Intent.EXTRA_SUBJECT, subject)
putExtra(Intent.EXTRA_TEXT, text)
}
feel free to replace Activity with Fragment if it suits your needs. Example usage:
if (hasEmailClient()) {
openEmailClient(
"example#email.info",
"this is the subject",
"this is the text"
)
}
This is what works for me:
val email = "recipient#email.com"
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:$email")
intent.putExtra(Intent.EXTRA_SUBJECT,"My Subject")
startActivity(intent)
First you should set the value of Intent.EXTRA_EMAIL as Array of Strings type like this:
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some#gmail.com" });
If this not works then simply uninstall the app and again Run....
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "xyx#gmail.com" });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
Related
I have the following intent -
binding.fragmentContactUsEmail.setOnClickListener {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "*/*"
putExtra(Intent.EXTRA_EMAIL, EMAIL)
putExtra(Intent.EXTRA_SUBJECT, "Team-It application feedback")
}
if (intent.resolveActivity(requireActivity().packageManager) != null) {
startActivity(intent)
}
}
Which does indeed open email intent.
The issue is that when trying to filter the intent using the docs from developer.android.com like this -
fun composeEmail(addresses: Array<String>, subject: String) {
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:") // only email apps should handle this
putExtra(Intent.EXTRA_EMAIL, addresses)
putExtra(Intent.EXTRA_SUBJECT, subject)
}
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
}
}
It failed the if statement like I do not have any email applications in my device, which is wrong as I do have one of them.
Another issue is that I can't get the Intent.EXTRA_EMAIL to work - it just does not add the e-mail addresses that should be delivered to, it leaves it blank.
What am I missing?
edit -
After trying a solution given to me in the comments, I was able to get the email send to an address but still title does not work.
Here is my current code -
binding.fragmentContactUsEmail.setOnClickListener {
val emailIntent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:${Constants.ApplicationContactInformation.EMAIL}")
putExtra(Intent.EXTRA_SUBJECT, "Feedback for Team-It")
}
if (emailIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivity(Intent.createChooser(emailIntent, ""))
} else {
Toast.makeText(requireContext(), getString(R.string.contact_us_fragment_no_email_applications), Toast.LENGTH_SHORT).show();
}
}
try this code :
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ "to"});
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "hi..");
//need this to prompts email client only
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
I'm using this code:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",email, null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, text);
activity.startActivity(Intent.createChooser(emailIntent, "Send feedback to xyz"));
for 2 years. And until now everything worked fine. User can select message client and send feedback with prefilled data inside. It worked fine for all mail clients.
Recently noticed that if I select gmail client - body of message remains empty, but on other mail clients body is filled with text.
Any ideas?
Thanks for help
Made tests with lots of suggested answers.
adding "text/plain" or "message/rfc822" made my app to stop offering mail clients.
Fount this answer that fixed my issue:
https://stackoverflow.com/a/59365539/973233
Most interesting part for me is having 2 intents:
Intent selectorIntent = new Intent(Intent.ACTION_SENDTO);
selectorIntent.setData(Uri.parse("mailto:"));
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, text);
emailIntent.setSelector( selectorIntent );
activity.startActivity(Intent.createChooser(emailIntent, "Send feedback to XYZ"));
This solved problem.
Recently i encountered the same issue. While searching, i found this as being the best solution (kotlin) (at least for myself):
fun sendEmail(email: String, subject: String, message: String) {
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.data = Uri.parse("mailto:")
emailIntent.type = "text/plain"
emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
emailIntent.putExtra(Intent.EXTRA_TEXT, message)
val sendIntent = Intent.createChooser(emailIntent, "Please Choose Email Client...")
sendIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
try {
context.startActivity(sendIntent)
} catch (e: Exception) {
Toast.makeText(context, e.message, Toast.LENGTH_LONG).show()
}
}
To send an email with a body, use message/rfc822.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("message/rfc822");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "to1#example.com", "to2#example.com" });
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject of the email");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Content of the email");
startActivity(sendIntent);
Hope this helps.
I'm using the following code and is working for every email client.
Example:
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"email id of receiver"});
intent.putExtra(Intent.EXTRA_SUBJECT, "This is the subject of the email client");
intent.putExtra(Intent.EXTRA_TEXT, "This is the body of the email client");
// this line is for attaching file
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Send Email"));
I use body properties for gmail and EXTRA_TEXT for other email. I've tested for different email app such as samsung email, oneplus email, and LG email, they seems to support EXTRA_TEXT but gmail is supporting "body" properties.
fun composeEmailMessage(context: Context, subject: String, body: String, emails: Array<String> = arrayOf()) {
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:")
intent.putExtra(Intent.EXTRA_EMAIL, emails)
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, body)//other emails app
intent.putExtra("body", body)//gmail
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(Intent.createChooser(intent, "Send email via..."))
}
}
I had similar issue. This worked for me: instead of
"mailto"
You have to use
"mailto:"
I have also replaced "Uri.fromParts" with "Uri.parse"
When I try to send an email Intent no matter if I am using INTENT.ACTION_SEND or ACTION.SENDTO and use the stock Sony Xperia Active email client the subject and the recipients show up fine but the body is empty except for the standard comment pasted by the client. On my Samsung Galaxy Note 2 the same code works like charm.
if(mPrefs.getBoolean("alternative_email_client", false)){
Intent send = new Intent(Intent.ACTION_SENDTO);
String uriText = "mailto:" + Uri.encode(emailStrings[6]) +
"?subject=" + Uri.encode("The subject") +
"&body=" + Uri.encode(emailBody);
Uri uri = Uri.parse(uriText);
send.setData(uri);
startActivity(Intent.createChooser(send, "Email verschicken"));
} else {
Intent send = new Intent(Intent.ACTION_SEND);
send.putExtra(Intent.EXTRA_EMAIL, emailStrings[6]);
send.putExtra(Intent.EXTRA_SUBJECT, "The Subject");
send.putExtra(Intent.EXTRA_TEXT, emailBody);
startActivity(Intent.createChooser(send, "Email verschicken"));
}
To send an email with a body, use message/rfc822.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("message/rfc822");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "to1#example.com", "to2#example.com" });
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject of the email");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Content of the email");
startActivity(sendIntent);
Hope this helps.
I use body properties for gmail and EXTRA_TEXT for other email. I've tested for different email app such as samsung email, oneplus email, and LG email, they seems to support EXTRA_TEXT but gmail is supporting "body" properties.
fun composeEmailMessage(context: Context, subject: String, body: String, emails: Array<String> = arrayOf()) {
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:")
intent.putExtra(Intent.EXTRA_EMAIL, emails)
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, body)//other emails app
intent.putExtra("body", body)//gmail
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(Intent.createChooser(intent, "Send email via..."))
}
}
Try to add the type of message
...
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, myMessage);
...
First create a selector. Important, that after "mailto:" leave it empty.
val selectorIntent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:")
}
Then the email intent itself:
val emailIntent = Intent(Intent.ACTION_SEND).apply {
putExtra(Intent.EXTRA_EMAIL, arrayOf("email#email.com"))
putExtra(Intent.EXTRA_SUBJECT, "This is a subject")
putExtra(Intent.EXTRA_TEXT, "Body text")
selector = selectorIntent
}
And open the email app:
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
}
(The solution is in kotlin)
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, "emailaddress#emailaddress.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
startActivity(Intent.createChooser(intent, "Send Email"));
The above code opens a dialog showing the following apps:- Bluetooth, Google Docs, Yahoo Mail, Gmail, Orkut, Skype, etc.
Actually, I want to filter these list options. I want to show only email-related apps e.g. Gmail, and Yahoo Mail. How to do it?
I've seen such an example on the 'Android Market application.
Open the Android Market app
Open any application where the developer has specified his/her email address. (If you can't find such an app just open my app:- market://details?id=com.becomputer06.vehicle.diary.free, OR search by 'Vehicle Diary')
Scroll down to 'DEVELOPER'
Click on 'Send Email'
The dialog shows only email Apps e.g. Gmail, Yahoo Mail, etc. It does not show Bluetooth, Orkut, etc. What code produces such dialog?
UPDATE
Official approach:
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);
}
}
Ref link
OLD ANSWER
The accepted answer doesn't work on the 4.1.2. This should work on all platforms:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","abc#gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
startActivity(Intent.createChooser(emailIntent, "Send email..."));
Update: According to marcwjj, it seems that on 4.3, we need to pass string array instead of a string for email address to make it work. We might need to add one more line:
intent.putExtra(Intent.EXTRA_EMAIL, addresses); // String[] addresses
There are three main approaches:
String email = /* Your email address here */
String subject = /* Your subject here */
String body = /* Your body here */
String chooserTitle = /* Your chooser title here */
1. Custom Uri:
Uri uri = Uri.parse("mailto:" + email)
.buildUpon()
.appendQueryParameter("subject", subject)
.appendQueryParameter("body", body)
.build();
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(Intent.createChooser(emailIntent, chooserTitle));
2. Using Intent extras:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + email));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
//emailIntent.putExtra(Intent.EXTRA_HTML_TEXT, body); //If you are using HTML in your body text
startActivity(Intent.createChooser(emailIntent, "Chooser Title"));
3. Support Library ShareCompat:
Activity activity = /* Your activity here */
ShareCompat.IntentBuilder.from(activity)
.setType("message/rfc822")
.addEmailTo(email)
.setSubject(subject)
.setText(body)
//.setHtmlText(body) //If you are using HTML in your body text
.setChooserTitle(chooserTitle)
.startChooser();
when you will change your intent.setType like below you will get
intent.setType("text/plain");
Use android.content.Intent.ACTION_SENDTO to get only the list of e-mail clients, with no facebook or other apps. Just the email clients.
Ex:
new Intent(Intent.ACTION_SENDTO);
I wouldn't suggest you get directly to the email app. Let the user choose his favorite email app. Don't constrain him.
If you use ACTION_SENDTO, putExtra does not work to add subject and text to the intent. Use Uri to add the subject and body text.
EDIT:
We can use message/rfc822 instead of "text/plain" as the MIME type. However, that is not indicating "only offer email clients" -- it indicates "offer anything that supports message/rfc822 data". That could readily include some application that are not email clients.
message/rfc822 supports MIME Types of .mhtml, .mht, .mime
This is quoted from Android official doc, I've tested it on Android 4.4, and works perfectly. See more examples at https://developer.android.com/guide/components/intents-common.html#Email
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);
}
}
A late answer, although I figured out a solution which could help others:
Java version
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:abc#xyz.com"));
startActivity(Intent.createChooser(emailIntent, "Send feedback"));
Kotlin version
val emailIntent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:abc#xyz.com")
}
startActivity(Intent.createChooser(emailIntent, "Send feedback"))
This was my output (only Gmail + Inbox suggested):
I got this solution from the Android Developers site.
This works for me:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "me#somewhere.com" });
intent.putExtra(Intent.EXTRA_SUBJECT, "My subject");
startActivity(Intent.createChooser(intent, "Email via..."));
Most importantly: Use the ACTION_SENDTO action rather than the ACTION_SEND action. I've tried it on a couple of Android 4.4 devices and:
It correctly limits the chooser pop-up to only display email applications (Email, Gmail, Yahoo Mail etc); and
It correctly inserts the email address and subject into the email.
Try:
intent.setType("message/rfc822");
This is the proper way to send the e-mail intent according to the Android Developer Official Documentation
Add these lines of code to your app:
Intent intent = new Intent(Intent.ACTION_SEND);//common intent
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
Optional: Add the body and subject, like this
intent.putExtra(Intent.EXTRA_SUBJECT, "Your Subject Here");
intent.putExtra(Intent.EXTRA_TEXT, "E-mail body" );
You already added this line in your question
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"hello#example.com"});
This will be the recipient's address, meaning the user will send you (the developer) an e-mail.
Finally come up with best way to do
String to = "test#gmail.com";
String subject= "Hi I am subject";
String body="Hi I am test body";
String mailTo = "mailto:" + to +
"?&subject=" + Uri.encode(subject) +
"&body=" + Uri.encode(body);
Intent emailIntent = new Intent(Intent.ACTION_VIEW);
emailIntent.setData(Uri.parse(mailTo));
startActivity(emailIntent);
Works on all android Versions:
String[] to = {"email#server.com"};
Uri uri = Uri.parse("mailto:email#server.com")
.buildUpon()
.appendQueryParameter("subject", "subject")
.appendQueryParameter("body", "body")
.build();
Intent emailIntent = new Intent(ACTION_SENDTO, uri);
emailIntent.putExtra(EXTRA_EMAIL, TO);
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Updated for Android 10, now using Kotlin...
fun Context.sendEmail(
address: String?,
subject: String?,
body: String?,
) {
val recipients = arrayOf(address)
val uri = address.toUri()
.buildUpon()
.appendQueryParameter("subject", subject)
.appendQueryParameter("body", body)
.build()
val emailIntent = Intent(ACTION_SENDTO, uri).apply {
setData("mailto:$address".toUri());
putExtra(EXTRA_SUBJECT, subject);
putExtra(EXTRA_TEXT, body);
putExtra(EXTRA_EMAIL, recipients)
}
val pickerTitle = getString(R.string.some_title)
ContextCompat.startActivity(this, Intent.createChooser(emailIntent, pickerTitle, null)
}
...after updating to API 30, the code did not fill the subject and body of the email client (e.g Gmail). But I found an answer here:
fun Context.sendEmail(
address: String?,
subject: String?,
body: String?,
) {
val selectorIntent = Intent(ACTION_SENDTO)
.setData("mailto:$address".toUri())
val emailIntent = Intent(ACTION_SEND).apply {
putExtra(EXTRA_EMAIL, arrayOf(address))
putExtra(EXTRA_SUBJECT, subject)
putExtra(EXTRA_TEXT, body)
selector = selectorIntent
}
startActivity(Intent.createChooser(emailIntent, getString(R.string.send_email)))
}
If you want only the email clients you should use android.content.Intent.EXTRA_EMAIL with an array. Here goes an example:
final Intent result = new Intent(android.content.Intent.ACTION_SEND);
result.setType("plain/text");
result.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { recipient });
result.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
result.putExtra(android.content.Intent.EXTRA_TEXT, body);
The following code works for me fine.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"abc#gmailcom"});
Intent mailer = Intent.createChooser(intent, null);
startActivity(mailer);
Edit: Not working anymore with new versions of Gmail
This was the only way I found at the time to get it to work with any characters.
doreamon's answer is the correct way to go now, as it works with all characters in new versions of Gmail.
Old answer:
Here is mine. It seems to works on all Android versions, with subject and message body support, and full utf-8 characters support:
public static void email(Context context, String to, String subject, String body) {
StringBuilder builder = new StringBuilder("mailto:" + Uri.encode(to));
if (subject != null) {
builder.append("?subject=" + Uri.encode(Uri.encode(subject)));
if (body != null) {
builder.append("&body=" + Uri.encode(Uri.encode(body)));
}
}
String uri = builder.toString();
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
context.startActivity(intent);
}
None of these solutions were working for me. Here's a minimal solution that works on Lollipop. On my device, only Gmail and the native email apps appear in the resulting chooser list.
Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
Uri.parse("mailto:" + Uri.encode(address)));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(emailIntent, "Send email via..."));
From Android developers docs:
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);
}
}
Most of these answers work only for a simple case when you are not sending attachment. In my case I need sometimes to send attachment (ACTION_SEND) or two attachments (ACTION_SEND_MULTIPLE).
So I took best approaches from this thread and combined them. It's using support library's ShareCompat.IntentBuilder but I show only apps which match the ACTION_SENDTO with "mailto:" uri. This way I get only list of email apps with attachment support:
fun Activity.sendEmail(recipients: List<String>, subject: String, file: Uri, text: String? = null, secondFile: Uri? = null) {
val originalIntent = createEmailShareIntent(recipients, subject, file, text, secondFile)
val emailFilterIntent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"))
val originalIntentResults = packageManager.queryIntentActivities(originalIntent, 0)
val emailFilterIntentResults = packageManager.queryIntentActivities(emailFilterIntent, 0)
val targetedIntents = originalIntentResults
.filter { originalResult -> emailFilterIntentResults.any { originalResult.activityInfo.packageName == it.activityInfo.packageName } }
.map {
createEmailShareIntent(recipients, subject, file, text, secondFile).apply { `package` = it.activityInfo.packageName }
}
.toMutableList()
val finalIntent = Intent.createChooser(targetedIntents.removeAt(0), R.string.choose_email_app.toText())
finalIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedIntents.toTypedArray())
startActivity(finalIntent)
}
private fun Activity.createEmailShareIntent(recipients: List<String>, subject: String, file: Uri, text: String? = null, secondFile: Uri? = null): Intent {
val builder = ShareCompat.IntentBuilder.from(this)
.setType("message/rfc822")
.setEmailTo(recipients.toTypedArray())
.setStream(file)
.setSubject(subject)
if (secondFile != null) {
builder.addStream(secondFile)
}
if (text != null) {
builder.setText(text)
}
return builder.intent
}
in Kotlin if anyone is looking
val emailArrray:Array<String> = arrayOf("travelagentsupport#kkk.com")
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:") // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, emailArrray)
intent.putExtra(Intent.EXTRA_SUBJECT, "Inquire about travel agent")
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
Following Code worked for me!!
import android.support.v4.app.ShareCompat;
.
.
.
.
final Intent intent = ShareCompat.IntentBuilder
.from(activity)
.setType("application/txt")
.setSubject(subject)
.setText("Hii")
.setChooserTitle("Select One")
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivity(intent);
This works for me perfectly fine:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("mailto:" + address));
startActivity(Intent.createChooser(intent, "E-mail"));
If you want to ensure that your intent is handled only by an email app (and not other text messaging or social apps), then use the ACTION_SENDTO action and include the "mailto:" data scheme. For example:
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);
}
}
I found this in https://developer.android.com/guide/components/intents-common.html#Email
Using intent.setType("message/rfc822"); does work but it shows extra apps that not necessarily handling emails (e.g. GDrive). Using Intent.ACTION_SENDTO with setType("text/plain") is the best but you have to add setData(Uri.parse("mailto:")) to get the best results (only email apps). The full code is as follows:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.setData(Uri.parse("mailto:IT#RMAsoft.NET"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Email from My app");
intent.putExtra(Intent.EXTRA_TEXT, "Place your email message here ...");
startActivity(Intent.createChooser(intent, "Send Email"));
If you want to target Gmail then you could do the following. Note that the intent is "ACTION_SENDTO" and not "ACTION_SEND" and the extra intent fields are not necessary for Gmail.
String uriText =
"mailto:youremail#gmail.com" +
"?subject=" + Uri.encode("your subject line here") +
"&body=" + Uri.encode("message body here");
Uri uri = Uri.parse(uriText);
Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
sendIntent.setData(uri);
if (sendIntent.resolveActivity(getPackageManager()) != null) {
startActivity(Intent.createChooser(sendIntent, "Send message"));
}
I am updating Adil's answer in Kotlin,
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:") // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, Array(1) { "test#email.com" })
intent.putExtra(Intent.EXTRA_SUBJECT, "subject")
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
showSnackBar(getString(R.string.no_apps_found_to_send_mail), this)
}
Kotlin:
val email: String = getEmail()
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:$email" )
startActivity(intent)
String sendEmailTo = "abc#xyz.com";
String subject = "Subject";
String body = "Body";
Uri uri = Uri.parse("mailto:"+sendEmailTo+"?subject="+subject+"&body="+body);
startActivity(new Intent(Intent.ACTION_VIEW, uri);
This worked for me. This will only show the mailing application in the intent chooser.
Additionally:
One problem that i faced with this method is I was unable to add space in the suggestions and body text.
So, to put spaces in the suggestion or body text then replace the space with %20
Please use the below code :
try {
String uriText =
"mailto:emailid" +
"?subject=" + Uri.encode("Feedback for app") +
"&body=" + Uri.encode(deviceInfo);
Uri uri = Uri.parse(uriText);
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(uri);
startActivity(Intent.createChooser(emailIntent, "Send email using..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(ContactUsActivity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
}
Maybe you should try this: intent.setType("plain/text");
I found it here. I've used it in my app and it shows only E-Mail and Gmail options.
Compose an email in the phone email client:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some#email.address" });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
Use this:
boolean success = EmailIntentBuilder.from(activity)
.to("support#example.org")
.cc("developer#example.org")
.subject("Error report")
.body(buildErrorReport())
.start();
use build gradle :
compile 'de.cketti.mailto:email-intent-builder:1.0.0'
This is what I use, and it works for me:
//variables
String subject = "Whatever subject you want";
String body = "Whatever text you want to put in the body";
String intentType = "text/html";
String mailToParse = "mailto:";
//start Intent
Intent variableName = new Intent(Intent.ACTION_SENDTO);
variableName.setType(intentType);
variableName.setData(Uri.parse(mailToParse));
variableName.putExtra(Intent.EXTRA_SUBJECT, subject);
variableName.putExtra(Intent.EXTRA_TEXT, body);
startActivity(variableName);
This will also let the user choose their preferred email app. The only thing this does not allow you to do is to set the recipient's email address.
I'm using Intent.ACTION_SEND to send an email. However, when I call the intent it is showing choices to send a message, send an email, and also to send via bluetooth. I want it to only show choices to send an email. How can I do this?
[Solution for API LEVEL >=15]
I've finally succeded in sending email WITH attachments to ONLY email clients.
I write it here because it took me a lot of time and it may be usefull to others.
The problem is:
Intent.ACTION_SENDTO takes Data URI (so you can specify "mailto:"
schema) BUT it does not accept Intent:EXTRA_STREAM.
Intent.ACTION_SEND accepts Intent:EXTRA_STREAM (so you can add
attachment) BUT it takes only Type (not Data URI so you cannot
specify "mailto:" schema).
So Intent.ACTION_SEND lets the user choose from several Activities, even if you setType("message/rfc822"), because that App/Activities can manage all file types (tipically GDrive/Dropbox Apps) and so even email message files.
The solution is in the setSelector method.
With this method you can use Intent.ACTION_SENDTO to select the Activity, but then send the Intent.ACTION_SEND Intent.
Here my solution code (the attachment came from a FileProvider, but it could be any file):
{
Intent emailSelectorIntent = new Intent(Intent.ACTION_SENDTO);
emailSelectorIntent.setData(Uri.parse("mailto:"));
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"address#mail.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
emailIntent.setSelector( emailSelectorIntent );
Uri attachment = FileProvider.getUriForFile(this, "my_fileprovider", myFile);
emailIntent.putExtra(Intent.EXTRA_STREAM, attachment);
if( emailIntent.resolveActivity(getPackageManager()) != null )
startActivity(emailIntent);
}
I'm not taking credit for this answer but I believe it gives the best answer for this post.
It's a common misconception to use text/plain or text/html. This will trigger any application that can handle plain or HTML text files without any context, including Google Drive, Dropbox, Evernote and Skype.
Instead use a ACTION_SENDTO, providing the mailto: Uri
intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
You can then proceed using the chooser as suggested through the other answers.
Answered by #PaulLammertsma here
Android email chooser
Intent email = new Intent(android.content.Intent.ACTION_SEND);
email.setType("application/octet-stream");
EDIT:
You could try setting the type to "message/rfc822" as well.
try this...
#Ganapathy:try this code for display gmail
Intent gmail = new Intent(Intent.ACTION_VIEW);
gmail.setClassName("com.google.android.gm","com.google.android.gm.ComposeActivityGmail");
gmail.putExtra(Intent.EXTRA_EMAIL, new String[] { "jckdsilva#gmail.com" });
gmail.setData(Uri.parse("jckdsilva#gmail.com"));
gmail.putExtra(Intent.EXTRA_SUBJECT, "enter something");
gmail.setType("plain/text");
gmail.putExtra(Intent.EXTRA_TEXT, "hi android jack!");
startActivity(gmail);
This will help you.
On your button click :
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"youremail#yahoo.com"});
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
Using message/rfc822 type as pointed here: ACTION_SEND force sending with email solves the issue.
I had a similar problem with my app. I recently found this link form the official android developers site that really helps!
Common Intents: Email
TL;DR:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
Now, you will only be shown email clients!
You can add a Subject and Body by doing this:
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Body" );
I notice, that this is an pretty old question but it is the first result when searching for a "Send mail" solution and all answers have a common problem:
Using Intent.ACTION_SEND and intent.setType("message/rfc822") will result in a chooser that not only shows mail apps but all apps that can handle any MIME type support by message/rfc822, e.g. .mhtml, .mht, .mime. Beside mail apps this could be Google Drive, Dropbox, Evernote, etc.
The only solution I found to limit the chooser to mail apps only is to use Intent.ACTION_SENDTO instead:
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto","address#example.com", null));
intent.putExtra(Intent.EXTRA_SUBJECT, "My Mail");
intent.putExtra(Intent.EXTRA_TEXT , "My Message");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
Thanks to the Open source developer, cketti for sharing this concise and neat solution. It's the only method that worked for me.
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
}
And this is the link to his/her gist.
First solution: try to be more specific in your Intent parameters. Add a message recipient for instance
emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"user#example.com"});
Second solution: use the package manager to find all applications capable of sending a message and select the only those you want to use.
Shout-out to ARLabs for posting the best solution on how to send an email on android. I just made a little update - an option to add multiple email attachements.
fun sendEmail(context: Context, recipients: List<String>?, subject: String?, body: String?, attachments: List<Uri>?) {
val emailIntent = Intent(Intent.ACTION_SEND_MULTIPLE)
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
emailIntent.selector = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"))
recipients?.let {
val recipientsArray = arrayOfNulls<String>(recipients.size)
ArrayList(recipients).toArray(recipientsArray)
emailIntent.putExtra(Intent.EXTRA_EMAIL, recipientsArray)
}
subject?.let {
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
}
body?.let {
emailIntent.putExtra(Intent.EXTRA_TEXT, body)
}
if (attachments?.isNotEmpty() == true) {
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(attachments))
}
try {
context.startActivity(emailIntent)
} catch (e: ActivityNotFoundException) {
// TODO handle "no app to handle action" error
}
}
This is a combination of Jack Dsilva and Jignesh Mayani solutions:
try
{
Intent gmailIntent = new Intent(Intent.ACTION_SEND);
gmailIntent.setType("text/html");
final PackageManager pm = _activity.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(gmailIntent, 0);
String gmailActivityClass = null;
for (final ResolveInfo info : matches)
{
if (info.activityInfo.packageName.equals("com.google.android.gm"))
{
gmailActivityClass = info.activityInfo.name;
if (gmailActivityClass != null && !gmailActivityClass.isEmpty())
{
break;
}
}
}
gmailIntent.setClassName("com.google.android.gm", gmailActivityClass);
gmailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "yourmail#gmail.com" });
gmailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
gmailIntent.putExtra(Intent.EXTRA_CC, "cc#gmail.com"); // if necessary
gmailIntent.putExtra(Intent.EXTRA_TEXT, "Email message");
gmailIntent.setData(Uri.parse("yourmail#gmail.com"));
this._activity.startActivity(gmailIntent);
}
catch (Exception e)
{
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "yourmail#gmail.com" });
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_CC, "cc#gmail.com"); // if necessary
i.putExtra(Intent.EXTRA_TEXT, "Email message");
i.setType("plain/text");
this._activity.startActivity(i);
}
So, at first it will try to open gmail app and in case a user doesn't have it then the second approach will be implemented.
Best code to restrict it to only send an email. set this type to only send an email. i.setType("message/rfc822");
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"skapis1#outlook.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(Firstclass.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
This saved my day. It sends composed text message directly to gmail app:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","togmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report message");
emailIntent.putExtra(Intent.EXTRA_TEXT, edt_msg.getText().toString());
startActivity(Intent.createChooser(emailIntent, "Send email..."));
This will open only the Email app installed in your android phone.
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"example#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "email subject");
intent.putExtra(Intent.EXTRA_TEXT, "message body");
try {
startActivity(Intent.createChooser(intent, "send mail"));
} catch (ActivityNotFoundException ex) {
Toast.makeText(this, "No mail app found!!!", Toast.LENGTH_SHORT);
} catch (Exception ex) {
Toast.makeText(this, "Unexpected Error!!!", Toast.LENGTH_SHORT);
}
public class MainActivity extends AppCompatActivity {
private EditText edt_email;
private Button btn_send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_email = (EditText) findViewById(R.id.edt_email);
btn_send = (Button) findViewById(R.id.btn_send);
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_SEND );
intent.putExtra(Intent.EXTRA_EMAIL , new String[]{"sanaebadi97#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT , "subject");
intent.putExtra(Intent.EXTRA_TEXT , "My Email Content");
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent , "Choose Your Account : "));
}
});
}
}
try with ACTION_VIEW not ACTION_SENDTO , ACTION_VIEW will makes system calls only to Email Apps
Intent emailIntent = new Intent(Intent.ACTION_VIEW);