Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีส่งอีเมลพร้อมไฟล์แนบใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีสร้างแอปส่งอีเมลพร้อมไฟล์แนบ โดยใช้ Intent.ACTION_SEND และเลือกไฟล์จากแกลเลอรี/ไฟล์ของอุปกรณ์

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: ออกแบบ Layout (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="อีเมลผู้รับ"
        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="หัวข้อ"
        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="เนื้อหาอีเมล"
        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="ส่ง" />

        <Button
            android:id="@+id/btAttachment"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:text="แนบไฟล์" />

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

ขั้นตอนที่ 3: เขียนโค้ด MainActivity (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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendEmail();
            }
        });

        btnAttachment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openFilePicker();
            }
        });
    }

    @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();
            tvAttachment.setText(attachmentUri.getLastPathSegment());
            tvAttachment.setVisibility(View.VISIBLE);
        }
    }

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

            if (email.isEmpty()) {
                Toast.makeText(this, "กรุณากรอกอีเมลผู้รับ", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            emailIntent.setType("message/rfc822");
            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, "ส่งอีเมลผ่าน..."));
        } catch (Exception e) {
            Toast.makeText(this, "เกิดข้อผิดพลาด: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*"); // รองรับทุกประเภทไฟล์
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(intent, "เลือกไฟล์แนบ"), PICK_FROM_GALLERY);
    }
}

ขั้นตอนที่ 4: 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>

การทดสอบ

รันแอป กรอกอีเมลผู้รับ หัวข้อ เนื้อหา กด "แนบไฟล์" เลือกไฟล์ จากนั้นกด "ส่ง" จะเปิดตัวเลือกแอปอีเมล (Gmail, Outlook, ฯลฯ)

วิธีส่งอีเมลพร้อมไฟล์แนบใน Android วิธีส่งอีเมลพร้อมไฟล์แนบใน Android