KotlinでAndroidアプリにファイル添付メール送信機能を実装する方法
この記事では、Kotlinを使用してAndroidアプリからファイル(画像)を添付したメールを送信する方法を、レイアウト・Kotlinコード・マニフェスト設定まで順を追って解説します。
ステップ1:新規プロジェクトの作成
まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。
ステップ2:レイアウトの作成(res/layout/activity_main.xml)
次に、メールの宛先・件名・本文を入力するEditTextと、「Send(送信)」「attachment(添付)」ボタンを配置したレイアウトを作成します。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="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_baseline_attach_file_24" android:visibility="gone" /> </LinearLayout>
このレイアウトでは、宛先用のEditText(etTo)、件名用(etSubject)、本文用(etMessage)に加え、送信ボタン(btSend)と添付ボタン(btAttachment)、選択した添付ファイル名を表示するTextView(tvAttachment)を定義しています。
ステップ3:MainActivity.ktの実装
続いて、src/MainActivity.ktに以下のコードを追加します。「attachment」ボタンをタップするとストレージからファイルを選択でき、「Send」ボタンで選択したファイルを添付したメールを送信できます。
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
lateinit var uri: Uri
private val pickFromGallery:Int = 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 {
openFolder()
}
}
private fun openFolder() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
intent.putExtra("return-data", true)
startActivityForResult(Intent.createChooser(intent, "Complete action using"), pickFromGallery)
}
private fun sendEmail() {
try {
email = etEmail.text.toString()
subject = etSubject.text.toString()
message = etMessage.text.toString()
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.type = "plain/text"
emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
emailIntent.putExtra(Intent.EXTRA_STREAM, uri)
emailIntent.putExtra(Intent.EXTRA_TEXT, message)
this.startActivity(Intent.createChooser(emailIntent, "Sending email..."))
}
catch (t: Throwable) {
Toast.makeText(this, "Request failed try again: $t", Toast.LENGTH_LONG).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == pickFromGallery && resultCode == RESULT_OK) {
if (data != null) {
uri = data.data!!
}
tvAttachment.text = uri.lastPathSegment
tvAttachment.visibility = View.VISIBLE
}
}
}
処理のポイント:
- openFolder():ACTION_GET_CONTENTインテントを使い、端末内の画像ファイルを選択させるセレクターを起動します。
- sendEmail():ACTION_SENDインテントでメールアプリを呼び出し、EXTRA_EMAIL(宛先)、EXTRA_SUBJECT(件名)、EXTRA_TEXT(本文)、EXTRA_STREAM(添付ファイルのUri)を設定します。
- onActivityResult():ファイル選択結果を受け取り、選択されたファイルのUriを保持して画面にファイル名を表示します。
補足:startActivityForResult/onActivityResultは現在非推奨(Deprecated)となっており、最新のAndroid開発ではActivity Result API(registerForActivityResult)の使用が推奨されています。既存コードの保守時には置き換えを検討してください。
ステップ4:AndroidManifest.xmlの設定
最後に、androidManifest.xmlにインターネット通信やストレージ読み取りに必要なパーミッションを追加します。以下のコードを追加してください。
<?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" /> <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端末をパソコンに接続しているものとして説明します。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの実行
アイコンをクリックします。表示される選択肢から自分のモバイルデバイスを選択すると、端末にアプリの初期画面が表示されます。



このように、Intent(ACTION_SEND)とEXTRA_STREAMを組み合わせるだけで、Kotlinを使ったファイル添付メール送信機能を簡単に実装できます。ぜひ自分のプロジェクトでも試してみてください。
-
【Android】ファイルを添付したメールを送信する方法を徹底解説
はじめにAndroidアプリからファイル(画像など)を添付したメールを送信したいと思ったことはありませんか?本記事では、宛先・件名・本文の入力フォームと添付ボタンを備えたシンプルなメール送信機能を、サンプルコードとともに段階的に解説します。手順通りに実装すれば、端末内のファイルを選択し、標準のメールアプリ経由で添付メールを送れるようになります。ステップ1:新規プロジェクトの作成まず、Android Studioで新しいプロジェクトを作成します。メニューから「File → New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。ステップ2:レイアウトファイル(
-
【Android】JavaMail APIを使用してメールを送信する方法を解説
はじめに この記事では、JavaMail APIを使用してAndroidアプリからメールを送信する方法を、ステップごとに詳しく解説します。画面に入力した宛先・件名・本文をもとに、GmailのSMTPサーバー経由でメールを送信するシンプルなサンプルアプリを作成していきます。 手順1:新規プロジェクトの作成 Android Studioを起動し、「File」→「New Project」を選択して、必要事項を入力して新しいプロジェクトを作成します。 手順2:レイアウトファイル(activity_main.xml)の作成 res/layout/activity_main.xmlに以下のコードを記述しま