Androidでメールを送信する方法

Androidでメールを送信する方法

Androidでは、Intent.ACTION_SENDを使用して、既存の電子メールクライアントを呼び出して電子メールを送信できます。

次のコードスニペットを参照してください。

    Intent email = new Intent(Intent.ACTION_SEND);
    email.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    email.putExtra(Intent.EXTRA_SUBJECT, "subject");
    email.putExtra(Intent.EXTRA_TEXT, "message");
    email.setType("message/rfc822");
    startActivity(Intent.createChooser(email, "Choose an Email client :"));

P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).

Run & test on real device only.
エミュレータでこれを実行すると、エラーメッセージ「No application can perform this action」が表示されます。 このコードは実際のデバイスでのみ機能します。

1. Androidのレイアウト

ファイル:res / layout / main.xml



    

    

        

    

    

    
    

    

    

    

2. アクティビティ

電子メールを送信するための完全なアクティビティクラス。 onClick()メソッドを読んでください。それは自明であるはずです。

package com.example.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SendEmailActivity extends Activity {

    Button buttonSend;
    EditText textTo;
    EditText textSubject;
    EditText textMessage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        buttonSend = (Button) findViewById(R.id.buttonSend);
        textTo = (EditText) findViewById(R.id.editTextTo);
        textSubject = (EditText) findViewById(R.id.editTextSubject);
        textMessage = (EditText) findViewById(R.id.editTextMessage);

        buttonSend.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

              String to = textTo.getText().toString();
              String subject = textSubject.getText().toString();
              String message = textMessage.getText().toString();

              Intent email = new Intent(Intent.ACTION_SEND);
              email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
              //email.putExtra(Intent.EXTRA_CC, new String[]{ to});
              //email.putExtra(Intent.EXTRA_BCC, new String[]{to});
              email.putExtra(Intent.EXTRA_SUBJECT, subject);
              email.putExtra(Intent.EXTRA_TEXT, message);

              //need this to prompts email client only
              email.setType("message/rfc822");

              startActivity(Intent.createChooser(email, "Choose an Email client :"));

            }
        });
    }
}

3. Demo

デフォルトの画面を見て、詳細を入力し、「送信」ボタンをクリックします。

send email in android

既存のメールクライアントに選択を促します。

send email in android

この場合、Gmailを選択すると、以前に詳細に入力されたものはすべて、Gmailクライアントに自動的に入力されます。

send email in android

Note
AndroidはEメールを直接送信するためのAPIを提供していません。Eメールを送信するには、既存のEメールクライアントを呼び出す必要があります。

ソースコードをダウンロード

ダウンロード–Android-Send-Email-Example.zip(16 KB)