Sunday, September 22, 2013

Send Email with Attachment in Android | Code for send email in Android | Sample demo for sending email in android with attachment

This is a simple demo for send email in Android with attachment. For attachment I am using Intent.ACTION_GET_CONTENT.
Don't forget to add permissions in your manifest.xml-

  <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" />



1)MainActivity.java

package com.manish.sendemaildemo;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 *
 * @author manish
 *
 */
public class MainActivity extends Activity implements OnClickListener {

       EditText editTextEmail, editTextSubject, editTextMessage;
       Button btnSend, btnAttachment;
       String email, subject, message, attachmentFile;
       Uri URI = null;
       private static final int PICK_FROM_GALLERY = 101;
       int columnIndex;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              editTextEmail = (EditText) findViewById(R.id.editTextTo);
              editTextSubject = (EditText) findViewById(R.id.editTextSubject);
              editTextMessage = (EditText) findViewById(R.id.editTextMessage);
              btnAttachment = (Button) findViewById(R.id.buttonAttachment);
              btnSend = (Button) findViewById(R.id.buttonSend);

              btnSend.setOnClickListener(this);
              btnAttachment.setOnClickListener(this);
       }

       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
                     /**
                      * Get Path
                      */
                     Uri selectedImage = data.getData();
                     String[] filePathColumn = { MediaStore.Images.Media.DATA };

                     Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
                     cursor.moveToFirst();
                     columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                     attachmentFile = cursor.getString(columnIndex);
                     Log.e("Attachment Path:", attachmentFile);
                     URI = Uri.parse("file://" + attachmentFile);
                     cursor.close();
              }
       }

       @Override
       public void onClick(View v) {

              if (v == btnAttachment) {
                     openGallery();

              }
              if (v == btnSend) {
                     try {
                           email = editTextEmail.getText().toString();
                           subject = editTextSubject.getText().toString();
                           message = editTextMessage.getText().toString();

                           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);
                           if (URI != null) {
                                  emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
                           }
                           emailIntent
                                         .putExtra(android.content.Intent.EXTRA_TEXT, message);
                           this.startActivity(Intent.createChooser(emailIntent,
                                         "Sending email..."));

                     } catch (Throwable t) {
                           Toast.makeText(this,
                                         "Request failed try again: " + t.toString(),
                                         Toast.LENGTH_LONG).show();
                     }
              }

       }

       public void openGallery() {
              Intent intent = new Intent();
              intent.setType("image/*");
              intent.setAction(Intent.ACTION_GET_CONTENT);
              intent.putExtra("return-data", true);
              startActivityForResult(
                           Intent.createChooser(intent, "Complete action using"),
                           PICK_FROM_GALLERY);

       }

}


2)activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:padding="5dp" >

        <EditText
            android:id="@+id/editTextTo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_margin="5dp"
            android:hint="Email Address!"
            android:inputType="textEmailAddress"
            android:singleLine="true" />

        <EditText
            android:id="@+id/editTextSubject"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/editTextTo"
            android:layout_margin="5dp"
            android:hint="Subject"
            android:singleLine="true" />

        <EditText
            android:id="@+id/editTextMessage"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@id/editTextSubject"
            android:layout_margin="5dp"
            android:gravity="top|left"
            android:hint="type message here!"
            android:inputType="textMultiLine" />

        <Button
            android:id="@+id/buttonSend"
            android:layout_width="80dp"
            android:layout_height="50dp"
            android:layout_below="@id/editTextMessage"
            android:layout_margin="5dp"
            android:text="Send" />

        <Button
            android:id="@+id/buttonAttachment"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="attachment" />
    </RelativeLayout>

</ScrollView>

3)AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.sendemaildemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <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="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.sendemaildemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thanks!


35 comments :

  1. HI manish have checked with working device the code was not performing any operations on it.

    ReplyDelete
    Replies
    1. It should work dear! I have tested it on many devices. Something wrong I think. Please check permission, package name.

      Delete
  2. Hi manish in this application give me error " No application can perform this action". how to solve it.

    thanks

    ReplyDelete
    Replies
    1. You are using emulator for testing? If you are using device please use some application for send email first like yahoo, gmail etc. You can sync a gmail account with your mobile or emulator...

      Thanks!

      Delete
  3. Hi manish,,, i got an error in mainactivity.java... "activity_main cannot be resolved or is not a field". how to solf it?

    thanks

    ReplyDelete
    Replies
    1. I think in your project R.java file is not created. please clean and re-build your project.

      Delete
  4. Hello manish, this s working .......this application want to test in device ......great work manish

    ReplyDelete
  5. hiii manishb great work...Can I send My sqlite data using it should display in table format in email

    ReplyDelete
    Replies
    1. You can't send it directly from sqite. You need to generate report first in pdf or any other format after that you can send as attachment.

      Delete
    2. Thank you manish..If I dont want use Third Party Api then there is any solution without using any Api can we save data in Html..if you have source code of how generate report in Android then please suggest

      Delete
    3. Sorry dear no idea. Well if you want do that you can use web-service to send your data on server and from there do what you want.

      Delete
  6. sry, i have a question :( it not run with my adt, can you send project to me dinhthehoa.aks@gmail.com i ready need it for big my homework. Please!!!!! Thank you

    ReplyDelete
    Replies
    1. Okay I am sending zip code please try to import into your workspace.

      Delete
  7. Hey email is going successfully but without an attachment.
    can you tell why is this happening?

    ReplyDelete
    Replies
    1. please check your log-cat is there path of image or not? may be your path==null.

      Delete
  8. This absolutely works. Thanks alot

    ReplyDelete
  9. hi manish
    i am new to this android coding
    i was trying for something else and i got this code i tried it, it is working fine but when i click on attachment it is directing me to gallery and if i click on any image it is not picking up the file plz help me
    thank you very much.

    ReplyDelete
  10. how to send image file as attachment from my project assets folder its very urgent can someone please help me

    ReplyDelete
  11. Sir, i want the zip file.
    i am new in android and unable to run this program perfectly . so, I need your help
    my email id : rshrwan@gmail.com

    ReplyDelete
    Replies
    1. Please copy paste from above it is very simple program. It should work properly. Actually I don't have this code on GIT server.

      Delete
  12. Hii Manish,

    How to add the images into emulator gallery?can you please let me know th esolution?

    ReplyDelete
    Replies
    1. Use DDMS in eclipse. Using DDMS you can put an image into your sdcard.

      Delete
  13. I always that I select a archive, Always get a error nullpointer : NOT WORK correctly al least > 4.0

    04-24 02:24:58.509: E/AndroidRuntime(9779): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=101, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:18 flg=0x1 }} to activity {com.manish.sendemaildemo/com.manish.sendemaildemo.MainActivity}: java.lang.NullPointerException: println needs a message

    ReplyDelete
    Replies
    1. As it shows nullpointer exception its mean your data is null when you trying to get onActivityResult.
      So use try catch here. And use any other method to get the url of image.

      Delete
  14. Hii manish i want to add my pdf files into attachment.....It can be possible to add pls help me ...
    thnx for before posts..

    ReplyDelete
    Replies
    1. Yes sure you can send any type of file. Just pass your URI of your PDF file.
      And for user Interface you need to implement chooser lib like yahoo mail app using.


      Delete
  15. This comment has been removed by the author.

    ReplyDelete
  16. Hii manish i want to add my pdf files into attachment.....It can be possible to adding attachment pls help me ...
    thnx for before posts..

    ReplyDelete
    Replies
    1. Yes sure you can send any type of file. Just pass your URI of image.
      And for user Interface you need to implement chooser lib like yahoo mail app using.

      Delete
  17. Hi manish, actually i'm in trouble with my small project, wil you help me with pick / send image to a mail id,(where i have camera interface from where i capture image and captured image should be sent to a particular (fixed) mail id ).. i'm new to android so facing lot of problems hope you eil help..

    ReplyDelete
  18. What if we want to pick image and send by one button only? This is you attach first and send. It should send immediately after attached. Any tutorial? Thank you.

    ReplyDelete
  19. hi manish, please help i just want the form to send the mail to a pre defined email

    ReplyDelete