Pages

Saturday, September 28, 2013

Send Email

In this post, you learn to create an e-mail sender app to send e-mail message and attached file from your Android smart phone to an e-mail address. Now open your Eclipse and create a new project call emailsender. For this app, we have the simple interface as shown in the screen shot below.

e-mail sender main interface


Views or components for this user interface are three EditText. One EditText allows the user to input the recipient e-mail address; One is to input the subject and another one is for inputting the message. The content of the main_layout.xml that is the resource of the user interface is shown below:

main_layout.xml file

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/mail_address"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/mail_address" />  

    <EditText
        android:id="@+id/mail_subject"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/mail_subject" />
 

    <EditText
        android:id="@+id/mail_text"
        android:layout_width="fill_parent"
        android:layout_height="200sp"
        android:hint="@string/mail_text"
        android:gravity="top"
        />

</LinearLayout>


The send and attach icons are placed on the action bar (see the picture above). By clicking the send icon on the action bar, a list of mail clients installed on your system is displayed to receive your message to send it to the recipient. The attach icon allows the user to attach a file to be sent along the e-mail message.
To setup action bar for the e-mail sender app, the SherlockActionBar library is used. If you don't know how to add this project library to your project, please read this TextViewer post.
When the user selects the attach icon from the action bar, a file chooser dialog shows up so that the user can choose any file that he/she wants to attach to the e-mail message. The FileChooser class that created in the previous post (FileChooser) is integrated with the e-mail sender app to show the file chooser dialog. The steps below tell you how to integrate the FileChooser with this app.

1. Copy the selection_style.xml, fileicon.png, and diricon.png files to the res/drawable directory
2. Copy the listlayout.xml file to the res/layout directory
3. Copy the AndFileChooser.java and ListAdapterModel.java files to the src directory and rename the package to match the package name of the e-mail sender app.
4. In the res/menu directory, replace the auto-generated main.xml file with the main.xml file from the FileChooser app.

e-mail sender showing file chooser


The AndroidManifest.xml file is modified to apply icon (mmail) and use the Shecklock sheme in the e-mail sender app. The content of this file is written as shown below.

AndroidManifest.xml file

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/mmail"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock.Light.DarkActionBar">
        <activity android:configChanges="orientation"
            android:name="com.example.emailsender.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>


Now, we take a look at the MainActivity.java file. In this file, code are written to display file chooser dialog and receive the selected file path, and to send the e-mail message.

MainActivity.java file

package com.example.emailsender;

import java.util.List;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import android.net.Uri;
import android.os.Bundle;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.widget.EditText;

public class MainActivity extends SherlockActivity {

AndFileChooser filechooser;
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
       
    }

@Override
    public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
        getSupportMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

   
    protected void onStart(){
    super.onStart();
    filechooser=new AndFileChooser("/",this); //create file chooser dialog
    }
   
    public void sendmail(){
    //get the selected file path
    String att_path=filechooser.getFilePath();
    //get address, subject, and message input by the user
    EditText txto=(EditText) findViewById(R.id.mail_address);
    EditText txtsubject=(EditText) findViewById(R.id.mail_subject);
    EditText txtmessage=(EditText) findViewById(R.id.mail_text);
    //create a Uri object to for the selected file path
    Uri urlpath=Uri.parse("file://"+att_path);
    //create an intent object for sending action
    Intent intent=new Intent(Intent.ACTION_SEND);
    //specify the minetype of the e-mail message
    intent.setType("*/*");    
    //put the recipient e-mail address in the intent object
    intent.putExtra(Intent.EXTRA_EMAIL,txto.getText().toString());
    //put the subject in the intent object
    intent.putExtra(Intent.EXTRA_SUBJECT,txtsubject.getText().toString());
    //put the message in the intent object
    intent.putExtra(Intent.EXTRA_TEXT,txtmessage.getText().toString());
    //put attached file in the intent object
    intent.putExtra(Intent.EXTRA_STREAM,urlpath);
    //Find available apps to receive the intent and start the intent if find one
    PackageManager pm=getPackageManager();
    List<ResolveInfo> vapps=pm.queryIntentActivities(intent, 0);
    if(vapps.size()>0){
    startActivity(Intent.createChooser(intent,"Send mail"));
    }
       
    }
   
    public void browse(){
   
    filechooser.show(); //show the file chooser dialog
   
   
    }
 
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch(item.getItemId()){
       
            case R.id.send: //send item is selected
            sendmail();
                break;

            case R.id.attach: //attach item is selected
            browse();
                break;

        }
       return true;
    }

   
   
}



In the onStart method, a AndFileChooser object is created by the following line of code.

filechooser=new AndFileChooser("/",this); //create file chooser dialog

To handle which item of the action bar is selected, you need to override the onOptionsItemSelected method. The switch... case statement is used to determine the selected item. The browse method is called to show the file chooser dialog when the selected item is the attach item. Otherwise, the sendmail method is called to send the e-mail message to the e-mail client.
In th sendmail method, the getPath method of the AndFileChooser object is used to get the path of the selected file. The e-mail data such as recipient e-mail address, subject, message, and attached file are collected and placed in the intent object to be sent to the mail client. You need to specify ACTION_SEND to the intent for e-mail sending. The PackageManager class to read the mail clients installed on the system and show a list of the available mail client apps. The startActivity method is called to start sending the e-mail message.
Now you are ready to run the e-mail sender app on your emulator. The apk file of this app is also provided through the link below so you can download and install it on your real device.

Download the apk file of the e-mail sender app

14 comments:

  1. chút hay không?

    Diệp Âm Trúc mỉm cười, lắc đầu, nói:
    -Mọi người tập trung tinh thần lực, đứng tại chỗ không cử động, chúng ta xuất phát ngay bây giờ.

    Quang mang chợt lóe, tử tinh cầu xuất hiện giữa thinh không, lơ lửng trên đầu Diệp Âm Trúc. Trừ Tô Lạp đã thấy qua, còn lại bốn người không khỏi toát ra ánh mắt kinh ngạc. Diệp Âm Trúc hai tay chắp lại, cường đại tinh thần lực từ giữa tinh thần lạc ấn xuất ra. Một vầng sáng màu tím nhất thời từ tử tinh cầu trên đỉnh đầu hắn phát ra rực rỡ, vầng sáng bao phủ hoàn toàn sáu người.
    Trong không gian pháp trận, xuất hiện vô số ấn chú màu tím sáng bóng, đối vối không gian hệ đệ tử như Thường Hạo, ánh mắt không khỏi xuất ra quang mang lấp lánh. đồng tâm
    game mu
    cho thuê nhà trọ
    cho thuê phòng trọ
    nhac san cuc manh
    số điện thoại tư vấn pháp luật miễn phí
    văn phòng luật
    tổng đài tư vấn pháp luật
    dịch vụ thành lập công ty
    http://we-cooking.com/
    chém gió
    trung tâm tiếng anh

    Tử quang chợt lóe, tổng cộng sáu đạo đồng thời chiếu lên mỗi người bọn họ, nguyên tố ba động, thân thể bọn họ biến mất giữa thinh không.
    Cực bắc hoang nguyên, mặc dù bây giờ đã là mùa xuân, nhưng độ ấm lại như trước khi băng điểm tan. Đột nhiên, sáu vòng sáng đồng thời xuất hiện, đem nhóm Diệp Âm Trúc xuất hiện. Ngoại trừ Diệp Âm Trúc đã có chuẩn bị , còn lại năm người đều có cảm giác toàn thân lạnh lẽo.

    ReplyDelete
  2. House cleaning company Khobar
    شركة تنظيف منازل بالدمام is the largest cleaning company in the Kingdom of Saudi Arabia, which provides a lot of services for cleaning apartments, villas and pest control services and many of the services needed by any houseشركة مكافحة حشرات بالدمام and the services of Anoud many of the advantages that will be enjoyed when you get the various cleaning services provided above

    شركة رش مبيدات بالدمام
    Level of quality and efficiency, and the company tops excellence is a شركة تنظيف موكيت بالدمام villas Khobar is specialized in all the work of cleaning houses, villas, buildings and apartments.
    شركة تنظيف كنب بالدمام
    If you have a suitable or come to you a guest soon, we are ready to fully equip and clean your home and make it as new and maintain it completely and clean it of dust and dirt attached and remove all things that are difficult to remove with materials removed without prejudice to any piece of furniture or damage it

    ReplyDelete
  3. This post is great n rich information. Keep writing good posts like this. Always supporting you torrents

    ReplyDelete
  4. شركة تركيب اثاث ايكيا بالرياض
    اسعار شركة تركيب اثاث ايكيا بالرياض
    شركة تركيب ستائر بالرياض
    محلات تركيب ستائر بالرياض
    فني تركيب باركية بالرياض
    شركة تركيب باركية بالرياض
    فني تركيب غرف نوم بالرياض
    شركة تركيب غرف نوم بالرياض
    شركة تركيب عفش بالرياض
    شركة تركيب اثاث بالرياض
    يحتاج تركيب الأثاث إلي شركات ذات خبرة كبيرة في ذلك المجال وكذلك إلي مجموعة من العمال القادرين علي التعامل مع كافة أنواع الأثاث والغرف، لذا توفر الشركة أفضل عامل تركيب أثاث بالرياض المدربين المحترفين والقادرين علي التعامل باحتراف شديد مع كافة أنواع الأثاث كما أن كافة عامل تركيب أثاث بالرياض مدربين على تركيب كافة أنواع الأثاث المنزلي دون التسبب في فساد أي جزء من تلك القطع المختلفة
    كما توفر شركة عامل تركيب أثاث بالرياض مجموعة كبيرة من السيارات الخاصة بنقل الأثاث وتتميز السيارة بأنها واسعة ونظيفة وكذلك عنصر الأمان فهي آمنة تماما علي الأثاث

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. This is really a great stuff for sharing. Keep it up . Thanks for sharing.
    gmail login

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
    Replies
  8. Good article! We will be linking to this great content on our website.
    WeRead For PC

    ReplyDelete
  9. I have read this post but I do not feel the need of your help because I am also one of the best writers of dissertation writing services who are serving the students for a long period.

    ReplyDelete