android-studiokotlinemailandroid-intentimagebutton

When I make an e-mail intent in kotlin, the recipient mail is not added directly


binding.navView.setNavigationItemSelectedListener {
            when(it.itemId){
                R.id.requestWallpaper->{
                    val emailIntent=Intent().apply {
                        action=Intent.ACTION_SEND
                        data= Uri.parse("mailto:")
                        type="text/plain"
                        putExtra(Intent.EXTRA_EMAIL,"test@gmail.com")
                        putExtra(Intent.EXTRA_SUBJECT,"request wallpaper")
                        putExtra(Intent.EXTRA_TEXT,"request wallpaper")
                    }
                    if (emailIntent.resolveActivity(this!!.packageManager) !=null){
                        emailIntent.setPackage("com.google.android.gm")
                        startActivity(emailIntent)
                    }else{
                        Toast.makeText(this@MainActivity,"No app available to send email!!",Toast.LENGTH_SHORT).show()
                    }
                }


When the navigation drawer opens, the user will want to make a wallpaper request and when he presses the imagebutton, I want him to send an e-mail to test@gmail.com via gmail for now, but test@gmail.com is not added directly to the "to" part of gmail.When I run it on the emulator, the email subject and e-mail text are added, but the recipient e-mail is not added, why?


Solution

  • You're so close here, the only thing that's missing is the Intent.EXTRA_EMAIL extra. That property is expecting an array of String values rather than a single String.

    binding.navView.setNavigationItemSelectedListener {
        when (it.itemId) {
            R.id.requestWallpaper -> {
                val emailIntent = Intent().apply {
                    action = Intent.ACTION_SEND
                    data = Uri.parse("mailto:")
                    type = "text/plain"
                    putExtra(Intent.EXTRA_EMAIL, arrayOf("test@gmail.com"))
                    putExtra(Intent.EXTRA_SUBJECT, "request wallpaper")
                    putExtra(Intent.EXTRA_TEXT, "request wallpaper")
                }
                if (emailIntent.resolveActivity(this.packageManager) != null) {
                    emailIntent.setPackage("com.google.android.gm")
                    startActivity(emailIntent)
                } else {
                    Toast.makeText(
                        this@MainActivity,
                        "No app available to send email!!",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }
    

    I don't know that you need the type="text/plain" property either, but it shouldn't hurt anything. Also, if you skip the setPackage step it'll allow the OS to ask which email app to use.