Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidアプリからGmailを使ってメールを送信する方法【サンプルコード付きで解説】

この記事では、AndroidアプリケーションからGmailなどのメールアプリを使ってメールを送信する方法を、実際のサンプルコードとともに段階的に解説します。

仕組みの概要

Androidでメールを送信する場合、Intent(インテント)を使用するのが一般的です。直接SMTPサーバーと通信するのではなく、「ACTION_SEND」という標準インテントを発行することで、端末にインストールされているGmailなどのメールアプリに送信処理を委ねます。この方法なら、認証情報をアプリ内に持つ必要がなく、安全かつ簡単に実装できます。

ステップ1:新規プロジェクトを作成する

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。

ステップ2:レイアウトファイル(activity_main.xml)を作成する

次に、res/layout/activity_main.xml に以下のコードを追加します。宛先メールアドレス・件名・本文を入力するためのEditTextと、送信用のButtonを配置したシンプルな縦方向のLinearLayoutです。

<?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="match_parent"
    android:padding="4dp"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Recipient email!" />

    <EditText
        android:id="@+id/editTextMail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subject"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextSubject"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextMessage"
        android:lines="4"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/buttonSend"
        android:text="Send" />
</LinearLayout>

ステップ3:MainActivity.javaに送信処理を実装する

続いて、src/MainActivity.java に以下のコードを追加します。ボタンがタップされると、入力された宛先・件名・本文を取得し、Intent経由でメールアプリを起動する仕組みです。

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity{

    EditText editTextMail, editTextSubject, editTextMessage;
    Button buttonSend;
    String email, subject, message;

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

        editTextMail = findViewById(R.id.editTextMail);
        editTextSubject = findViewById(R.id.editTextSubject);
        editTextMessage = findViewById(R.id.editTextMessage);

        buttonSend = findViewById(R.id.buttonSend);

        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_EMAIL, new String(email));
                intent.putExtra(Intent.EXTRA_SUBJECT, subject);
                intent.putExtra(Intent.EXTRA_TEXT, message);

                intent.setType("message/rfc822");
                startActivity(Intent.createChooser(intent, "Select email"));
            }
        });
    }

    private void getData() {
        email = editTextMail.getText().toString();
        subject = editTextSubject.getText().toString();
        message = editTextMessage.getText().toString();
    }
}

コードのポイント

Intent.ACTION_SEND:メール送信などデータを他アプリへ渡すための標準アクションです。
EXTRA_EMAIL / EXTRA_SUBJECT / EXTRA_TEXT:それぞれ宛先・件名・本文を格納するエクストラです。
setType("message/rfc822"):MIMEタイプを指定することで、セレクターに表示される候補をGmailなどのメールアプリだけに絞り込めます。
Intent.createChooser():ユーザーが使用するメールアプリを選択できるダイアログを表示します。

ステップ4:AndroidManifest.xmlを確認する

最後に、androidManifest.xml に以下のコードを記述します。特別なパーミッションは不要ですが、MainActivityがランチャーアクティビティとして登録されていることを確認してください。

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

    <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からアプリを起動するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーのRunアイコンをクリックします。表示された選択肢から自分のモバイルデバイスを選ぶと、端末に以下のような初期画面が表示されます。

AndroidアプリからGmailを使ってメールを送信する方法【サンプルコード付きで解説】


宛先・件名・本文を入力して「Send」ボタンをタップすると、メールアプリの選択ダイアログが表示されます。Gmailを選択すれば、入力内容がそのまま反映された状態で送信画面が立ち上がります。

AndroidアプリからGmailを使ってメールを送信する方法【サンプルコード付きで解説】


このように、Intentを活用すれば数行のコードでAndroidアプリへのメール送信機能を組み込めます。ぜひ実際に試してみてください。

  1. 【保存版】Googleスプレッドシート×Gmailで一括メール送信を実現する方法(YAMM活用ガイド)

    連絡先リストに対して一件ずつ個別にメールを送るのは、パーソナライズを求めるほど膨大な時間がかかってしまいます。作業だけで一日が終わってしまうようでは、こうしたキャンペーンを続けるメリットも見出せません。 そこでおすすめなのが、Googleスプレッドシートのアドオン「Yet Another Mail Merge(YAMM)」です。連絡先リスト・スプレッドシート・Gmailの3つさえあれば、何百件ものパーソナライズ済みメールを一括で送信できます。 Yet Another Mail Mergeをダウンロードする YAMMでは無料で最大50通までメールを送信できます。まずは公式サイトにアクセスしてアプ

  2. GmailとOutlookで暗号化メールを安全に送信する方法を徹底解説

    セキュリティは、現代社会における最大の関心事の一つです。SNSであれメールであれ、プライバシーへの脅威は常にインターネット上に潜んでいます。そのため、悪質なサイバー犯罪者から大切な情報を守るために、メールを暗号化することが非常に重要になっています。 メールの送受信は私たちの日常的なタスクです。だからこそ、添付ファイルやメール本文をしっかりと暗号化して保護する意識を持つ必要があります。例えば、ProtonMailのようなアプリを使えば、送信するメールが自動的に暗号化されるため安心です。しかし、普段使っているOutlookやGmailで安全なメールを送る方法をご存知でしょうか? 本記事では、暗号化