I am new to programming. Trying to open Gmail using this code snippet. But problem is putExtra(Intent.EXTRA_EMAIL, strTo) does not give any result. putExtra(Intent.EXTRA_SUBJECT, strSubject) works fine. I tried to pass array also but result is same. Could someone please give suggestions for this email sender using kotlin.
val etTo = findViewById<EditText>(R.id.etTo)
val etSubject = findViewById<EditText>(R.id.etSubject)
val emailBtn = findViewById<Button>(R.id.emailBtn)
emailBtn.setOnClickListener {
val strTo = etTo.text.toString()
val strSubject = etSubject.text.toString()
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto")
putExtra(Intent.EXTRA_EMAIL, strTo)
putExtra(Intent.EXTRA_SUBJECT, strSubject)
startActivity(intent,)
composeEmail("$strTo", "$strSubject")
}
}
fun composeEmail(addresses: String, subject: String) {
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:")
putExtra(Intent.EXTRA_EMAIL, addresses)
putExtra(Intent.EXTRA_SUBJECT, subject)
}
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
}
}
I tried using array.
fun composeEmail(addresses: Array, subject: String)
CodePudding user response:
val intent = Intent(Intent.ACTION_SEND).apply {
type = "message/rfc822"
putExtra(Intent.EXTRA_EMAIL, arrayOf(strTo))
putExtra(Intent.EXTRA_SUBJECT, strSubject)
}
startActivity(intent)
You need to use the type property to specify the type of data you are sending, and that you need to pass the recipient's email address as an array of strings. Keep in mind that using this method will only open the user's default email app with the recipient's email address and subject pre-filled. The user will still need to write and send the email manually.
CodePudding user response:
It looks like you're trying to pass a string to putExtra(Intent.EXTRA_EMAIL, strTo)
instead of an array of strings. The Intent.EXTRA_EMAIL
constant is used to pass an array of email addresses to an email app, so you'll need to pass it an array of strings in the format "[email protected]".
Here's an example of how you could modify your code to use an array of strings:
val emailBtn = findViewById<Button>(R.id.emailBtn)
emailBtn.setOnClickListener {
val strTo = etTo.text.toString()
val strSubject = etSubject.text.toString()
// Create an array of strings with the email address entered in the etTo EditText
val emailAddresses = arrayOf(strTo)
// Use the array of email addresses to pass to putExtra()
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto")
putExtra(Intent.EXTRA_EMAIL, emailAddresses)
putExtra(Intent.EXTRA_SUBJECT, strSubject)
startActivity(intent,)
}
composeEmail(emailAddresses, "$strSubject")
}