Pages

Tuesday, February 11, 2014

Android: How to send email from android application

Create a Linear xml layout as below,

In Android, we can use Intent.ACTION_SEND to call an existing email client to send an email.
Below shows the complete code for sending an email.
package com.example.sampletestapp;

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

public class SendMail extends Activity {

    EditText edtTo, edtSub, edtMsgs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sendemail);
        initializeVars();
    }
    private void initializeVars() {

        edtTo = (EditText) findViewById(R.id.edtTo);
        edtSub = (EditText) findViewById(R.id.edtSubj);
        edtMsgs = (EditText) findViewById(R.id.edtMsg);
    }
     //emailSend() set to onClick() of Send Mail button in xml layout
    public void emailSend(View v) {
        String message = edtMsgs.getText().toString();
        String to=edtTo.getText().toString();
        String subj=edtSub.getText().toString();

        Intent emailIntent=new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, to);
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subj);
        emailIntent.setType("plain/text");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
        startActivity(emailIntent);       
    }
}
Run the application and fill in all the fields and click Send Mail button.

The screen will be displayed as,

Check the email and message will be received successfully.

No comments:

Post a Comment