Manish Srivastava

About 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.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

6 Responses to "Send Email with Attachment in Android"

  1. needHelp says:

    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.

  2. keerthi says:

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

  3. Daisy says:

    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

  4. Marcos says:

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

  5. Amal says:

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

  6. Fashnl says:

    I am getting errors with this code :(

Leave a Reply


five × 2 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close