Hướng dẫn này minh họa cách gửi email kèm file đính kèm (attachment) trong Android sử dụng Kotlin.
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://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="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:hint="Email người nhận"
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="Tiêu đề"
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="Nội dung 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="Gửi" />
<Button
android:id="@+id/btAttachment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:text="Đính kèm" />
</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>
Bước 3: Viết code 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
var uri: Uri? = null
private val PICK_FROM_GALLERY = 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 { openFilePicker() }
}
private fun openFilePicker() {
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
putExtra("return-data", true)
}
startActivityForResult(Intent.createChooser(intent, "Chọn ứng dụng"), PICK_FROM_GALLERY)
}
private fun sendEmail() {
try {
email = etEmail.text.toString()
subject = etSubject.text.toString()
message = etMessage.text.toString()
val emailIntent = Intent(Intent.ACTION_SEND).apply {
type = "plain/text"
putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
putExtra(Intent.EXTRA_SUBJECT, subject)
putExtra(Intent.EXTRA_TEXT, message)
uri?.let { putExtra(Intent.EXTRA_STREAM, it) }
}
startActivity(Intent.createChooser(emailIntent, "Gửi email qua..."))
} catch (t: Throwable) {
Toast.makeText(this, "Gửi thất bại: $t", Toast.LENGTH_LONG).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
data?.data?.let {
uri = it
tvAttachment.text = uri?.lastPathSegment
tvAttachment.visibility = View.VISIBLE
}
}
}
}
Bước 4: Cấu hình AndroidManifest.xml (cần quyền)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://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" />
<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>
</intent-filter>
</activity>
</application>
</manifest>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Nhập email, subject, nội dung. Nhấn "Đính kèm" chọn ảnh từ gallery. Nhấn "Gửi" → Mở chooser chọn app email (Gmail, Outlook...).
Giải thích Intent.ACTION_SEND
| Extra | Kiểu | Mô tả |
|---|---|---|
EXTRA_EMAIL | String[] | Danh sách email người nhận |
EXTRA_CC | String[] | Email CC |
EXTRA_BCC | String[] | Email BCC |
EXTRA_SUBJECT | String | Tiêu đề email |
EXTRA_TEXT | String | Nội dung (plain text) |
EXTRA_STREAM | Uri | File đính kèm (Uri content://) |
EXTRA_HTML_TEXT | String | Nội dung HTML (API 16+) |
Gửi nhiều file đính kèm
val uris: ArrayList= arrayListOf(uri1, uri2, uri3) val emailIntent = Intent(Intent.ACTION_SEND_MULTIPLE).apply { type = "*/*" putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris) // ... other extras }
Lưu ý Android 10+ (Scoped Storage)
- Không cần
READ_EXTERNAL_STORAGEkhi dùngACTION_GET_CONTENT/ACTION_OPEN_DOCUMENT- Uri trả về là
content://(không phảifile://)- Email app cần hỗ trợ content Uri (Gmail, Outlook hỗ trợ tốt)