Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách gửi email HTML từ ứng dụng Android bằng Kotlin

Giới thiệu

Ví dụ minh họa cách gửi email định dạng HTML từ ứng dụng Android bằng Intent.ACTION_SENDTO và Html.fromHtml() trong Kotlin. Ứng dụng sẽ mở trình chọn email client (Gmail, Outlook, v.v.) với nội dung HTML đã định dạng.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio > File > New Project.

Bước 2: Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="sendHtmlEmail"
        android:text="Gửi Email HTML" />

</RelativeLayout>

Bước 3: MainActivity.kt

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Html
import android.view.View
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
    }

    fun sendHtmlEmail(view: View?) {
        val mailId = "yourmail@gmail.com" // Thay bằng email nhận thực tế
        val emailIntent = Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", mailId, null))

        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Chủ đề email từ App")
        // Nội dung HTML
        val htmlBody = """
            

Xin chào,

Đây là email HTML gửi từ ứng dụng Android Kotlin.

Link đến Google

Trân trọng,
App Demo

""".trimIndent() emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(htmlBody, Html.FROM_HTML_MODE_LEGACY)) // Html.FROM_HTML_MODE_LEGACY (API < 24) hoặc FROM_HTML_MODE_COMPACT / SEPARATOR (API 24+) startActivity(Intent.createChooser(emailIntent, "Gửi email qua...")) } }

Bước 4: AndroidManifest.xml

Không cần quyền đặc biệt cho ACTION_SENDTO.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.sendhtmlmail">

    <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>

Chạy ứng dụng

Chạy app, nhấn nút "Gửi Email HTML". Hộp thoại chọn app email hiện ra. Chọn Gmail/Outlook, email sẽ mở với nội dung HTML đã định dạng (in đậm, nghiêng, link, chữ nhỏ).

Lưu ý quan trọng

  • ACTION_SENDTO với scheme mailto: chỉ mở app email. ACTION_SEND mở thêm các app chia sẻ khác (Bluetooth, Drive, v.v.).
  • Không phải email client nào cũng hỗ trợ đầy đủ HTML/CSS. Gmail hỗ trợ tốt, một số client chỉ render cơ bản.
  • CSS inline (style="...") an toàn hơn thẻ <style>.
  • Hình ảnh: Dùng URL tuyệt đối (https://...) hoặc attach file (Intent.EXTRA_STREAM) - phức tạp hơn.
  • Html.fromHtml(): Dùng HtmlCompat.fromHtml() từ androidx.core.text.HtmlCompat để tương thích mọi API level.

Gửi email ngầm (Background) - Không mở client

Android không cho phép gửi email hoàn toàn ngầm (background) mà không có sự tương tác của người dùng vì lý do bảo mật/spam. Các giải pháp thay thế:

  1. Backend API: App gửi dữ liệu lên server của bạn, server dùng SMTP (JavaMail, SendGrid, Mailgun, v.v.) gửi email. An toàn, kiểm soát được.
  2. Intent.ACTION_SEND: Vẫn cần user bấm "Gửi" trên client email.
  3. AccountManager + Auth: Rất phức tạp, cần quyền đặc biệt, không khuyến khích.

Ví dụ Backend (Khái niệm)

// App (Retrofit/OkHttp)
@POST("api/send-email")
suspend fun sendEmail(@Body request: EmailRequest): Response

// Server (Spring Boot / Node.js / Python)
POST /api/send-email {
  to: "user@example.com",
  subject: "Chủ đề",
  htmlBody: "Nội dung HTML"
}
// Server dùng JavaMailSender / Nodemailer gửi đi