Android Core

Send Email with Attachment in Android

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

Screenshot_2013-09-23-00-07-49

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!
 

Reference: Send Email with Attachment in Android from our JCG partner Manish Srivastava at the Android Hub 4 you blog.

Manish Srivastava

I have been a mobile software consultant + developer(Java, J2ME, Android) for over 2 years. I have done enterprise level development for large and small companies alike. Around 2010,I started doing Development for my customers.I always build clean, mobile friendly, semantic applicattion for every customer. For my clients, I get 100% involved, dedicated to making sure they get the best performance from the appliaction. I strive for long term results. I truly enjoy Mobile Development, and am very passionate about it. This enables me to do the best job for my clients.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
needHelp
needHelp
10 years ago

Thanks for the above tutorial,

But How can we read email with Attachments in Android App.

As we can read Complete Mail on Gmail’s Own App.

Thanks A lot again.

Waiting for Your Reply.

keerthi
keerthi
10 years ago

i’m new for android…. i need code for displaying DAT file……

Daisy
Daisy
10 years ago

i have one problem..

i added this to my app but i can’t make it work

i made new activity and added this to AndroidManifest

<activity
android:name=".ContactusActivity"

also i did the other but not working… it’s workin when i make contactusActivity the default activity… how i can run it along with the other activities?

thanks

Marcos
Marcos
10 years ago

Hello, how can we do the same thing but this time for a word document ??

Amal
Amal
9 years ago

How can i send an email in background in android studio?

Fashnl
Fashnl
9 years ago

I am getting errors with this code :(

arihant
arihant
9 years ago

in above code only image can attached how we do for any doc file or other file

suresh
suresh
9 years ago
Reply to  arihant

open gallery()
{

emailIntent.setType(“*/*”);

}

Devloper
Devloper
9 years ago

Sir! The code almost works fine… But, whenever i send email or compose it.. It shows me “Successfully! sent”… (I had added a alert) but the message doesn’t actually sent.. I had checked mailbox and even Spambox but no message there sent via this app.

Please feedback this query with a valid solution.

imran
imran
8 years ago

how can i fetch this attachment in my android app from gmial. can you send me code.

Ali
Ali
8 years ago

Hi, your app basically just inserts data into another e-mail app, can you show how to send the e-mail from within the app (automated) using for example JavaMail API or some other method?

Waseem Akram
Waseem Akram
8 years ago

Hey Dear, i am new in android. i have made an application that communicate between user by text messages using sockets and xampp server. now i want to attach some files like image and send it to other user… please help me…. thanks for any help…

andreas
andreas
8 years ago

This simply doesn’t work. I get a null on the attachmentFile after choosing an image.

mano
mano
8 years ago
Reply to  andreas

Have you figured it out?

varunlokesh
8 years ago

showStatusIcon on inactive InputConnection

varunlokesh
8 years ago
Reply to  varunlokesh

showStatusIcon on inactive InputConnection(plz help me with this error)

varunlokesh
8 years ago
Reply to  varunlokesh

not able to attach file

imgur
7 years ago

It means that you get total discounts at the time
of subscription. You will also need to delegate your domain name to
the hosting space, details on this are provided
by your hosting provider. The amount of space required by a website should also
be considered while choosing a web host.

sudheer
sudheer
7 years ago

image file is working but word document is not attaching what can i do

Mehul
Mehul
6 years ago

im getting error in cursor.movetofirst() how to solve

Back to top button