Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드(Android)에서 파일 첨부 이메일 보내는 방법 – 단계별 구현 가이드

이 튜토리얼에서는 안드로이드 앱에서 파일을 첨부한 이메일을 보내는 방법을 단계별로 살펴봅니다. 수신자 이메일 주소, 제목, 본문을 입력하고, 갤러리에서 파일을 선택해 첨부한 뒤 이메일 앱으로 전송하는 전체 과정을 예제 코드와 함께 설명합니다.

구현 단계

1단계: 새 프로젝트 생성

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 세부 정보를 모두 입력하여 프로젝트를 만듭니다.

2단계: 레이아웃 작성 (res/layout/activity_main.xml)

메인 화면에는 수신자 이메일 주소 입력란, 제목 입력란, 본문 작성란, 그리고 전송(Send) 버튼과 첨부(attachment) 버튼을 배치합니다. 아래 코드를 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="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_attach"
      android:visibility="gone" />
</LinearLayout>

3단계: 메인 액티비티 코드 작성 (src/MainActivity.java)

이제 핵심 로직을 구현합니다. ACTION_SEND 인텐트를 사용해 이메일 앱을 호출하고, EXTRA_STREAM에 선택한 파일의 URI를 담아 첨부 파일을 전달합니다. 아래 코드를 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;
   EditText etSubject;
   EditText etMessage;
   Button Send;
   Button attachment;
   TextView tvAttachment;
   String email;
   String subject;
   String message;
   Uri URI = 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);
      attachment = findViewById(R.id.btAttachment);
      tvAttachment = findViewById(R.id.tvAttachment);
      Send = findViewById(R.id.btSend);
      Send.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            sendEmail();
         }
      });
      //attachment button listener
      attachment.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            openFolder();
         }
      });
   }
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
         URI = data.getData();
         tvAttachment.setText(URI.getLastPathSegment());
         tvAttachment.setVisibility(View.VISIBLE);
      }
   }
   public void sendEmail() {
      try {
         email = etEmail.getText().toString();
         subject = etSubject.getText().toString();
         message = etMessage.getText().toString();
         final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
         emailIntent.setType("plain/text");
         emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email});
         emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
         if (URI != null) {
            emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
         }
         emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
         this.startActivity(Intent.createChooser(emailIntent, "Sending email..."));
      } catch (Throwable t) {
         Toast.makeText(this, "Request failed try again: "+ t.toString(), Toast.LENGTH_LONG).show();
      }
   }
   public void openFolder() {
      Intent intent = new Intent();
      intent.setType("image/*");
      intent.setAction(Intent.ACTION_GET_CONTENT);
      intent.putExtra("return-data", true);
      startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
   }
}

핵심 코드 설명

  • openFolder(): ACTION_GET_CONTENT 액션과 "image/*" MIME 타입을 지정해 갤러리에서 이미지를 선택하도록 파일 탐색기를 엽니다.
  • onActivityResult(): 갤러리에서 파일을 선택하면 그 결과 URI를 받아와 화면에 첨부 파일 이름을 표시합니다.
  • sendEmail(): EXTRA_EMAIL(수신자), EXTRA_SUBJECT(제목), EXTRA_TEXT(본문)를 인텐트에 담고, 첨부 파일이 있으면 EXTRA_STREAM으로 전달한 뒤 createChooser()를 통해 이메일 앱을 실행합니다.

4단계: 매니페스트 권한 설정 (androidManifest.xml)

인터넷 통신과 외부 저장소의 파일 읽기를 위해 아래와 같이 필요한 권한을 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" />
   <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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 실행(Run) 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기에 아래와 같은 기본 화면이 표시됩니다.

안드로이드(Android)에서 파일 첨부 이메일 보내는 방법 – 단계별 구현 가이드

수신자 이메일 주소와 제목, 본문을 입력한 후 attachment 버튼을 눌러 갤러리에서 파일을 선택하면, 첨부된 파일 이름이 화면에 나타납니다. 마지막으로 Send 버튼을 누르면 기기에 설치된 이메일 앱(Gmail 등)이 열리며 첨부 파일이 포함된 이메일이 준비됩니다.

안드로이드(Android)에서 파일 첨부 이메일 보내는 방법 – 단계별 구현 가이드