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

Cách gửi email kèm tệp đính kèm trong Android

Giới thiệu

Bài viết này hướng dẫn xây dựng màn hình soạn thảo email cho phép nhập người nhận, chủ đề, nội dung, chọn tệp đính kèm từ bộ nhớ thiết bị và gửi qua ứng dụng email mặc định (Gmail, Outlook...). Sử dụng Intent.ACTION_SEND với EXTRA_STREAM cho tệp đính kèm.

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

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

Mở Android Studio, chọn File → New Project và tạo dự án.

Bước 2: Thiết kế giao diện (res/layout/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="Địa chỉ 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="Chủ đề"
        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_attach"
        android:visibility="gone" />

</LinearLayout>

Bước 3: Viết code logic (src/MainActivity.java)

import android.app.Activity;
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;

public class MainActivity extends Activity {
    EditText etEmail, etSubject, etMessage;
    Button btnSend, btnAttachment;
    TextView tvAttachment;
    Uri attachmentUri = null;
    private static final int PICK_FROM_GALLERY = 101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etEmail = findViewById(R.id.etTo);
        etSubject = findViewById(R.id.etSubject);
        etMessage = findViewById(R.id.etMessage);
        btnAttachment = findViewById(R.id.btAttachment);
        tvAttachment = findViewById(R.id.tvAttachment);
        btnSend = findViewById(R.id.btSend);

        btnSend.setOnClickListener(v -> sendEmail());

        btnAttachment.setOnClickListener(v -> openFilePicker());
    }

    private void sendEmail() {
        try {
            String email = etEmail.getText().toString().trim();
            String subject = etSubject.getText().toString().trim();
            String message = etMessage.getText().toString().trim();

            if (email.isEmpty()) {
                Toast.makeText(this, "Vui lòng nhập email người nhận", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            emailIntent.setType("message/rfc822"); // MIME type chuẩn cho email
            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
            emailIntent.putExtra(Intent.EXTRA_TEXT, message);

            if (attachmentUri != null) {
                emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri);
                emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }

            startActivity(Intent.createChooser(emailIntent, "Gửi email qua..."));
        } catch (Exception e) {
            Toast.makeText(this, "Lỗi: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*"); // Cho phép chọn mọi loại file
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
        startActivityForResult(Intent.createChooser(intent, "Chọn tệp đính kèm"), PICK_FROM_GALLERY);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK && data != null) {
            attachmentUri = data.getData();
            if (attachmentUri != null) {
                tvAttachment.setText("Đã chọn: " + attachmentUri.getLastPathSegment());
                tvAttachment.setVisibility(View.VISIBLE);
            }
        }
    }
}

Bước 4: Cấu hình quyền trong AndroidManifest.xml

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

    <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>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập email người nhận, chủ đề, nội dung, nhấn "Đính kèm" để chọn file, sau đó nhấn "Gửi". Hệ thống sẽ mở hộp thoại chọn ứng dụng email (Gmail, Outlook...).

Lưu ý quan trọng

  • Dùng message/rfc822 thay vì plain/text để chỉ mở các app email
  • Android 10+ không cần quyền READ_EXTERNAL_STORAGE khi dùng Storage Access Framework (ACTION_GET_CONTENT)
  • Luôn thêm FLAG_GRANT_READ_URI_PERMISSION khi đính kèm Uri từ ContentProvider
  • Hỗ trợ nhiều tệp: dùng ACTION_SEND_MULTIPLE và EXTRA_STREAM là ArrayList<Uri>