How to send an email with a file attachment in Android using Kotlin?

Kotlin AndroidApps/ApplicationsMobile Development

This example demonstrates how to send an email with a file attachment in Android using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical"
   android:padding="4dp"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/etTo"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="5dp"
      android:hint="Receiver's Email Address!"
      android:inputType="textEmailAddress"
      android:singleLine="true" />
   <EditText
      android:id="@+id/etSubject"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="5dp"
      android:hint="Enter Subject"
      android:singleLine="true" />
   <EditText
      android:id="@+id/etMessage"
      android:layout_width="match_parent"
      android:layout_height="200dp"
      android:layout_margin="5dp"
      android:gravity="top|start"
      android:hint="Compose Email"
      android:inputType="textMultiLine" />
   <RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
   <Button
      android:id="@+id/btSend"
      android:layout_width="80dp"
      android:layout_height="50dp"
      android:layout_margin="5dp"
      android:text="Send" />
   <Button
      android:id="@+id/btAttachment"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentEnd="true"
      android:text="attachment" />
   </RelativeLayout>
   <TextView
      android:id="@+id/tvAttachment"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:drawableStart="@drawable/ic_baseline_attach_file_24"
      android:visibility="gone" />
</LinearLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   lateinit var etEmail: EditText
   lateinit var etSubject: EditText
   lateinit var etMessage: EditText
   lateinit var send: Button
   lateinit var attachment: Button
   lateinit var tvAttachment: TextView
   lateinit var email: String
   lateinit var subject: String
   lateinit var message: String
   lateinit var uri: Uri
   private val pickFromGallery:Int = 101
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      etEmail = findViewById(R.id.etTo)
      etSubject = findViewById(R.id.etSubject)
      etMessage = findViewById(R.id.etMessage)
      attachment = findViewById(R.id.btAttachment)
      tvAttachment = findViewById(R.id.tvAttachment)
      send = findViewById(R.id.btSend)
      send.setOnClickListener { sendEmail() }
      attachment.setOnClickListener {
         openFolder()
      }
   }
   private fun openFolder() {
      val intent = Intent()
      intent.type = "image/*"
      intent.action = Intent.ACTION_GET_CONTENT
      intent.putExtra("return-data", true)
      startActivityForResult(Intent.createChooser(intent, "Complete action using"), pickFromGallery)
   }
   private fun sendEmail() {
      try {
         email = etEmail.text.toString()
         subject = etSubject.text.toString()
         message = etMessage.text.toString()
         val emailIntent = Intent(Intent.ACTION_SEND)
         emailIntent.type = "plain/text"
         emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
         emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
         emailIntent.putExtra(Intent.EXTRA_STREAM, uri)
         emailIntent.putExtra(Intent.EXTRA_TEXT, message)
         this.startActivity(Intent.createChooser(emailIntent, "Sending email..."))
      }
      catch (t: Throwable) {
         Toast.makeText(this, "Request failed try again: $t", Toast.LENGTH_LONG).show()
      }
   }
   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
      super.onActivityResult(requestCode, resultCode, data)
      if (requestCode == pickFromGallery && resultCode == RESULT_OK) {
         if (data != null) {
            uri = data.data!!
         }
         tvAttachment.text = uri.lastPathSegment
         tvAttachment.visibility = View.VISIBLE
      }
   }
}

Step 4 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.q11">
   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run Play Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

raja
Published on 18-Aug-2020 12:29:22
Advertisements