Just Simple Info

Pages

Android Send Email


Android send email

Sometimes our android application need to send email  for whatever reason.

So this time I going to post a simple code snippet on how android application can send email.
I make this code simple. No xml coding in this post.


Below is the structure of our project.



Here are the codes in MainActivity.java.


import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Toast;


public class MainActivity extends Activity {
 final static int REQUEST_CODE = 16;
 Uri imageUri;
 Layout layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.layout = new Layout(this);
        setContentView(this.layout);
    }
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){
   
  
   Uri selectedImage = data.getData();
   String[] projection = { MediaStore.Images.Media.DATA };
   Cursor cursor = getContentResolver().query(selectedImage, projection, null, null, null);
   
   cursor.moveToFirst();
   
   int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
   
   //*** GET IMAGE PATH
   String imagePath = cursor.getString(index);
   
   //*** SET Uri
   this.imageUri = Uri.parse("file://" + imagePath);
   
   //*** DISPLAY IMAGE
   this.displayImage(imagePath);
   
  }
  
 }
 /**
  * Display image to  ImageView
  * @param imagePath
  */
 private void displayImage(String imagePath){
  File imageFile = new File(imagePath);
  Bitmap bmp = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
  
  layout.attachmentImage.setImageBitmap(bmp);
 }
 /**
  * Show gallery of images
  * @param context
  */
  protected static void showGalleryImages(Context context) {
         Intent intent = new Intent();
         intent.setType("image/*");
         intent.setAction(Intent.ACTION_GET_CONTENT);
         intent.putExtra("return-data", true);
         
         ((MainActivity)context).startActivityForResult(Intent.createChooser(intent, "Select image"),MainActivity.REQUEST_CODE);

  }
  /**
   * Sent email
   * @param imageUri
   * @param layout
   */
  protected static void sendMail(Uri imageUri, Layout layout){
   try {
             String email = layout.recepientEditText.getText().toString().trim();
             String subject = layout.subjectEditText.getText().toString().trim();
             String message = layout.messageEditText.getText().toString().trim();

             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);
             emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
             
             if (imageUri != null) {
              //*** ADD THE IMAGE 
                 emailIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
             }
             //*** SET IMAGE
             ((MainActivity)layout.getContext()).startActivity(Intent.createChooser(emailIntent,"Sending..."));

       } catch (Exception e) {
        e.printStackTrace();
           Toast.makeText(layout.getContext(), "Failed to sent", Toast.LENGTH_SHORT).show();
       }
 }


   
}

Here is the code in Layout.java.


import android.content.Context;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Layout extends LinearLayout implements OnClickListener {
 
 final static String SELECT_ATTACHMENT_LBL = "Select attachement";
 final static String SEND_LBL = "Sent";
 
 EditText recepientEditText;
 EditText subjectEditText;
 EditText messageEditText;
 ImageView attachmentImage;
 Button saveButton;
 Button selectAttachment;
 

 public Layout(Context context) {
  super(context);
  
  //*** SET ORIENTATION VERTICAL
  this.setOrientation(LinearLayout.VERTICAL);
  
  this.initComponents();
 }
 
 private void initComponents(){
  
  this.recepientEditText = new EditText(this.getContext());
  this.recepientEditText.setHint("email address");
  this.recepientEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
  
  this.subjectEditText = new EditText(this.getContext());
  //this.subjectEditText.setInputType(InputType.TYPE_CLASS_TEXT);
  this.subjectEditText.setSingleLine();
  this.subjectEditText.setHint("subject");
  
  this.messageEditText = new EditText(this.getContext());
  this.messageEditText.setHint("message");
  this.messageEditText.setSingleLine(false);
  this.messageEditText.setLines(3);
  this.messageEditText.setGravity(Gravity.TOP);
  this.messageEditText.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
  
  this.attachmentImage = new ImageView(this.getContext());
  this.attachmentImage.setLayoutParams(new LinearLayout.LayoutParams(250,250));
  this.selectAttachment = new Button(getContext());
  this.selectAttachment.setText(SELECT_ATTACHMENT_LBL);
  this.selectAttachment.setTag(SELECT_ATTACHMENT_LBL);
  
  this.saveButton = new Button(getContext());
  this.saveButton.setText(SEND_LBL);
  this.saveButton.setTag(SEND_LBL);
  
  
  //*** SET CLICK LISTENER
  this.selectAttachment.setOnClickListener(this);
  this.saveButton.setOnClickListener(this);
  
  //*** ADD COMPONENTS
  this.addView(this.recepientEditText);
  this.addView(this.subjectEditText);
  this.addView(this.messageEditText);
  this.addView(this.attachmentImage);
  this.addView(this.selectAttachment);
  this.addView(this.saveButton);
  
  
  
  
 }

 @Override
 public void onClick(View view) {
  String VIEW_TAG = view.getTag().toString();
  
  if(VIEW_TAG.equalsIgnoreCase(SELECT_ATTACHMENT_LBL)){
   
   //*** SHOW GALLERY
   MainActivity.showGalleryImages(this.getContext());
   
  }else if(VIEW_TAG.equalsIgnoreCase(SEND_LBL)){
   
   String email = this.recepientEditText.getText().toString().trim();
   
   if(!this.isEmailValid(email)){
    
    //*** CHECK IF EMAIL IS VALID
    
    Toast.makeText(getContext(), "not a valid email", Toast.LENGTH_SHORT).show();
   
   }
   
   MainActivity mainActivity = (MainActivity) getContext();
   
   //*** SEND EMAIL
   MainActivity.sendMail(mainActivity.imageUri, this);
   
   
  }else{
   //*** UNKNOWN TAG
  }
  
 }
 /**
  * Check if valid email
  * @param email
  * @return
  */
 boolean isEmailValid(CharSequence email) {
  return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
 }
 
 
 

}

 now we have a simple android application that can send email.

Download source code here.


Good luck and hope in helps.

No comments:

Post a Comment