Send Email using Intent - Android Studio - Compose

How To Send an Email Using the Intent

Learn how to implement email functionality in your Android app using Kotlin Compose and Android Studio IDE. This step-by-step guide covers using Android Intents to launch email clients with pre-filled recipient addresses, subjects, and message bodies.

>> Check For Java

Code:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <!--For Gmail Intent: Since Android 11 (API level 30), most user-installed apps are not visible by default.
    In your manifest, you must statically declare which apps you are going to get info about, as in the following:-->
    <queries>
        <package android:name="com.google.android.gm" />
    </queries>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

MainActivity.kt

package com.technifysoft.myapplication

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.technifysoft.myapplication.ui.theme.MyApplicationTheme

class MainActivityCompose : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainUi(
                onSendEmail = { recipient, subject, message ->
                    sendEmail(recipient, subject, message)
                }
            )
        }
    }

    private fun sendEmail(recipient: String, subject: String, message: String) {
        //call email share method
        val gmailPackage = "com.google.android.gm"
        // return true if gmail is installed
        val isGmailInstalled = isAppInstalled(gmailPackage)

        /*ACTION_SEND action to launch an email client installed on your Android device.*/
        val intent = Intent(Intent.ACTION_SEND)
        // put recipient email in intent
        /* recipient is put as array because you may wanna send email to multiple emails
           so enter comma(,) separated emails, it will be stored in array*/
        intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(recipient))
        //put subject of email
        intent.putExtra(Intent.EXTRA_SUBJECT, subject)
        //put message of email in intent
        intent.putExtra(Intent.EXTRA_TEXT, message)
        if (isGmailInstalled) {
            intent.type = "text/html"
            intent.setPackage(gmailPackage)
            startActivity(intent)
        } else {
            // allow user to choose a different app to send email with
            intent.type = "message/rfc822"
            startActivity(Intent.createChooser(intent, "choose an email client"))
        }
    }

    private fun isAppInstalled(packageName: String): Boolean {
        return try {
            packageManager.getApplicationInfo(packageName, 0)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }
}

@Composable
fun MainUi(
    onSendEmail: (String, String, String) -> Unit
) {
    val context = LocalContext.current

    var recipient by remember { mutableStateOf("") }
    var subject by remember { mutableStateOf("") }
    var message by remember { mutableStateOf("") }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {

        Text(
            modifier = Modifier
                .padding(vertical = 40.dp)
                .fillMaxWidth(),
            text = "Send Email",
            style = TextStyle(textAlign = TextAlign.Center)
        )

        // Recipient
        OutlinedTextField(
            value = recipient,
            onValueChange = { recipient = it },
            label = { Text("Recipient email(s)") },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
            modifier = Modifier.fillMaxWidth()
        )

        Spacer(modifier = Modifier.height(10.dp))

        // Subject
        OutlinedTextField(
            value = subject,
            onValueChange = { subject = it },
            label = { Text("Subject") },
            modifier = Modifier.fillMaxWidth()
        )

        Spacer(modifier = Modifier.height(10.dp))

        // Message
        OutlinedTextField(
            value = message,
            onValueChange = { message = it },
            label = { Text("Enter message here...") },
            modifier = Modifier
                .fillMaxWidth()
                .height(150.dp),
            maxLines = 6
        )

        Spacer(modifier = Modifier.height(16.dp))

        // Button
        Button(
            onClick = {
                onSendEmail(recipient.trim(), subject.trim(), message.trim())
            },
            modifier = Modifier.align(androidx.compose.ui.Alignment.End)
        ) {
            Text("Send Email")
        }
    }

}


/**
 * GreetingPreview is a composable function for previewing the MainUI in Android Studio.
 * It is annotated with @Preview to enable live preview.
 *
 */
@Preview(showBackground = true)
@Composable
private fun GreetingPreview() {
    MyApplicationTheme {
        //MainUi()
    }
}

Screenshots:






Comments

Popular posts from this blog

Picture In Picture - Android Studio - Kotlin

Manage External Storage Permission - Android Studio - Kotlin

How to add AIDL folder | Android Studio