Tuesday, 11 December 2012

Sending An e-mail with attachment in my Phonegap Android Application

EmailActivity.java

package com.lkr.androidemail;

import org.apache.cordova.DroidGap;

import android.os.Bundle;

public class EmailActivity extends DroidGap {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }

}

WebIntent.java


package com.borismus.webintent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.cordova.DroidGap;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.text.Html;
import android.view.View;

/**
 * WebIntent is a PhoneGap plugin that bridges Android intents and web
 * applications:
 * 
 * 1. web apps can spawn intents that call native Android applications. 2.
 * (after setting up correct intent filters for PhoneGap applications), Android
 * intents can be handled by PhoneGap web applications.
 * 
 * @author boris@borismus.com
 * 
 */
public class WebIntent extends Plugin {

    private String onNewIntentCallback = null;

    /**
     * Executes the request and returns PluginResult.
     * 
     * @param action
     *            The action to execute.
     * @param args
     *            JSONArray of arguments for the plugin.
     * @param callbackId
     *            The callback id used when calling back into JavaScript.
     * @return A PluginResult object with a status and message.
     */
    public PluginResult execute(String action, JSONArray args, String callbackId) {
        try {
            if (action.equals("startActivity")) {
                if (args.length() != 1) {
                    return new PluginResult(PluginResult.Status.INVALID_ACTION);
                }

                // Parse the arguments
                JSONObject obj = args.getJSONObject(0);
                String type = obj.has("type") ? obj.getString("type") : null;
                Uri uri = obj.has("url") ? Uri.parse(obj.getString("url")) : null;
                JSONObject extras = obj.has("extras") ? obj.getJSONObject("extras") : null;
                Map<String, String> extrasMap = new HashMap<String, String>();

                // Populate the extras if any exist
                if (extras != null) {
                    JSONArray extraNames = extras.names();
                    for (int i = 0; i < extraNames.length(); i++) {
                        String key = extraNames.getString(i);
                        String value = extras.getString(key);
                        extrasMap.put(key, value);
                    }
                }

                startActivity(obj.getString("action"), uri, type, extrasMap);
                return new PluginResult(PluginResult.Status.OK);

            } else if (action.equals("hasExtra")) {
                if (args.length() != 1) {
                    return new PluginResult(PluginResult.Status.INVALID_ACTION);
                }
                Intent i = ((DroidGap)this.cordova.getContext()).getIntent();
                String extraName = args.getString(0);
                return new PluginResult(PluginResult.Status.OK, i.hasExtra(extraName));

            } else if (action.equals("getExtra")) {
                if (args.length() != 1) {
                    return new PluginResult(PluginResult.Status.INVALID_ACTION);
                }
                Intent i = ((DroidGap)this.cordova.getContext()).getIntent();
                String extraName = args.getString(0);
                if (i.hasExtra(extraName)) {
                    return new PluginResult(PluginResult.Status.OK, i.getStringExtra(extraName));
                } else {
                    return new PluginResult(PluginResult.Status.ERROR);
                }
            } else if (action.equals("getUri")) {
                if (args.length() != 0) {
                    return new PluginResult(PluginResult.Status.INVALID_ACTION);
                }

                Intent i = ((DroidGap)this.cordova.getContext()).getIntent();
                String uri = i.getDataString();
                return new PluginResult(PluginResult.Status.OK, uri);
            } else if (action.equals("onNewIntent")) {
                if (args.length() != 0) {
                    return new PluginResult(PluginResult.Status.INVALID_ACTION);
                }

                this.onNewIntentCallback = callbackId;
                PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
                result.setKeepCallback(true);
                return result;
            } else if (action.equals("sendBroadcast")) 
            {
                if (args.length() != 1) {
                    return new PluginResult(PluginResult.Status.INVALID_ACTION);
                }

                // Parse the arguments
                JSONObject obj = args.getJSONObject(0);

                JSONObject extras = obj.has("extras") ? obj.getJSONObject("extras") : null;
                Map<String, String> extrasMap = new HashMap<String, String>();

                // Populate the extras if any exist
                if (extras != null) {
                    JSONArray extraNames = extras.names();
                    for (int i = 0; i < extraNames.length(); i++) {
                        String key = extraNames.getString(i);
                        String value = extras.getString(key);
                        extrasMap.put(key, value);
                    }
                }

                sendBroadcast(obj.getString("action"), extrasMap);
                return new PluginResult(PluginResult.Status.OK);
            }
            return new PluginResult(PluginResult.Status.INVALID_ACTION);
        } catch (JSONException e) {
            e.printStackTrace();
            return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (this.onNewIntentCallback != null) {
            PluginResult result = new PluginResult(PluginResult.Status.OK, intent.getDataString());
            result.setKeepCallback(true);
            this.success(result, this.onNewIntentCallback);
        }
    }

    void startActivity(String action, Uri uri, String type, Map<String, String> extras) {
        Intent i = (uri != null ? new Intent(action, uri) : new Intent(action));
        
        if (type != null && uri != null) {
            i.setDataAndType(uri, type); //Fix the crash problem with android 2.3.6
        } else {
            if (type != null) {
                i.setType(type);
            }
        }
        
        for (String key : extras.keySet()) {
            String value = extras.get(key);
            // If type is text html, the extra text must sent as HTML
            if (key.equals(Intent.EXTRA_TEXT) && type.equals("text/html")) {
                i.putExtra(key, Html.fromHtml(value));
            } else if (key.equals(Intent.EXTRA_STREAM)) {
             // image naming and path  to include sd card
                String mPath = Environment.getExternalStorageDirectory().toString() + "/abc.png";   

                // create bitmap screen capture
                Bitmap bitmap;
                View v1 = this.ctx.getActivity().getCurrentFocus();
                v1.setDrawingCacheEnabled(true);
                bitmap = Bitmap.createBitmap(v1.getDrawingCache());
                v1.setDrawingCacheEnabled(false);

                OutputStream fout = null;
                File imageFile = new File(mPath);

                try {
                    fout = new FileOutputStream(imageFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
                    fout.flush();
                    fout.close();

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
             
                // allowes sharing of images as attachments.
                // value in this case should be a URI of a file
                
                System.out.println("image path is:"+mPath);
             System.out.println("streammmmmmm:"+Intent.EXTRA_STREAM);
                i.putExtra(key, Uri.parse(value));
            } else if (key.equals(Intent.EXTRA_EMAIL)) {
                // allows to add the email address of the receiver
                i.putExtra(Intent.EXTRA_EMAIL, new String[] { value });
            } else {
                i.putExtra(key, value);
            }
        }
        this.cordova.getActivity().startActivity(i);
    }

    void sendBroadcast(String action, Map<String, String> extras) {
        Intent intent = new Intent();
        intent.setAction(action);
        for (String key : extras.keySet()) {
            String value = extras.get(key);
            intent.putExtra(key, value);
        }

        ((DroidGap)this.cordova.getContext()).sendBroadcast(intent);
    }
}

index.html


<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>

<script src="cordova-2.0.0.js"></script>
<script src="webintent.js"></script>


 <script>

function gomail(){
 alert("mail going");
 var extras = {};
   extras[WebIntent.EXTRA_SUBJECT] = "subject";
   extras[WebIntent.EXTRA_TEXT] = "body";
   extras[WebIntent.EXTRA_STREAM]="file:///mnt/sdcard/abc.png";
   WebIntent.prototype.startActivity({ 
       action: WebIntent.ACTION_SEND,
       type: 'application/octet-stream', 
       extras: extras 
     }, 
     function() {
      alert("success");
     }, 
     function() {
       alert('Failed to send email via Android Intent');
     }
   ); 
}
</script>
 

</head>
<body>
  
   <div>
  
   <h1>Email sending</h1>

<a href="#" onclick="gomail();">emailll</a>
  
 </div>   
  
 
</body>
</html>

webintent.js


/**
 * cordova Web Intent plugin
 * Copyright (c) Boris Smus 2010
 *
 */
var WebIntent = function() { 

};

WebIntent.ACTION_SEND = "android.intent.action.SEND";
WebIntent.ACTION_VIEW= "android.intent.action.VIEW";
WebIntent.EXTRA_TEXT = "android.intent.extra.TEXT";
WebIntent.EXTRA_SUBJECT = "android.intent.extra.SUBJECT";
WebIntent.EXTRA_STREAM = "android.intent.extra.STREAM";
WebIntent.EXTRA_EMAIL = "android.intent.extra.EMAIL";

WebIntent.prototype.startActivity = function(params, success, fail) {
 alert("webintent");
 return cordova.exec(function(args) {
        success(args);
    }, function(args) {
        fail(args);
    }, 'WebIntent', 'startActivity', [params]);
};

WebIntent.prototype.hasExtra = function(params, success, fail) {
 return cordova.exec(function(args) {
        success(args);
    }, function(args) {
        fail(args);
    }, 'WebIntent', 'hasExtra', [params]);
};

WebIntent.prototype.getUri = function(success, fail) {
 return cordova.exec(function(args) {
        success(args);
    }, function(args) {
        fail(args);
    }, 'WebIntent', 'getUri', []);
};

WebIntent.prototype.getExtra = function(params, success, fail) {
 return cordova.exec(function(args) {
        success(args);
    }, function(args) {
        fail(args);
    }, 'WebIntent', 'getExtra', [params]);
};


WebIntent.prototype.onNewIntent = function(callback) {
 return cordova.exec(function(args) {
  callback(args);
    }, function(args) {
    }, 'WebIntent', 'onNewIntent', []);
};

WebIntent.prototype.sendBroadcast = function(params, success, fail) {
    return cordova.exec(function(args) {
        success(args);
    }, function(args) {
        fail(args);
    }, 'WebIntent', 'sendBroadcast', [params]);
};

cordova.addConstructor(function() {
 window.webintent = new WebIntent();
 
 // backwards compatibility 
 window.plugins = window.plugins || {};
 window.plugins.webintent = window.webintent;
});

config.xml


<?xml version="1.0" encoding="utf-8"?>
<!--
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
-->
<cordova>
    <!--
    access elements control the Android whitelist.
    Domains are assumed blocked unless set otherwise
     -->

    <access origin="http://127.0.0.1*"/> <!-- allow local pages -->

    <!-- <access origin="https://example.com" /> allow any secure requests to example.com -->
    <!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www -->
    <!-- <access origin=".*"/> Allow all domains, suggested development use only -->

    <log level="DEBUG"/>
    <preference name="useBrowserHistory" value="false" />
<plugins>
    <plugin name="App" value="org.apache.cordova.App"/>
    <plugin name="Geolocation" value="org.apache.cordova.GeoBroker"/>
    <plugin name="Device" value="org.apache.cordova.Device"/>
    <plugin name="Accelerometer" value="org.apache.cordova.AccelListener"/>
    <plugin name="Compass" value="org.apache.cordova.CompassListener"/>
    <plugin name="Media" value="org.apache.cordova.AudioHandler"/>
    <plugin name="Camera" value="org.apache.cordova.CameraLauncher"/>
    <plugin name="Contacts" value="org.apache.cordova.ContactManager"/>
    <plugin name="File" value="org.apache.cordova.FileUtils"/>
    <plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/>
    <plugin name="Notification" value="org.apache.cordova.Notification"/>
    <plugin name="Storage" value="org.apache.cordova.Storage"/>
    <plugin name="Temperature" value="org.apache.cordova.TempListener"/>
    <plugin name="FileTransfer" value="org.apache.cordova.FileTransfer"/>
    <plugin name="Capture" value="org.apache.cordova.Capture"/>
    <plugin name="Battery" value="org.apache.cordova.BatteryListener"/>
    <plugin name="SplashScreen" value="org.apache.cordova.SplashScreen"/>
    <plugin name="WebIntent" value="com.borismus.webintent.WebIntent"/>
</plugins>
</cordova>

AndroidManifest.xml



<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lkr.androidemail"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true" />

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".EmailActivity"
            android:label="@string/title_activity_email" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

20 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. thanks for post but i having issue the same post
    can you plz send me demo example for send mail with attach.
    my email id is mayur.loved@gmail.com

    ReplyDelete
    Replies
    1. @Mayur Check your mail once, i sent it to u

      Delete
  3. thanks for post too. but i could't run it as error in the java file..
    can you plz send me demo example for send mail with attach.
    my email id is koihafiz@gmail.com

    ReplyDelete
  4. Hai KR...so sorry for delay,plenty of works to be done. Thanks for the email apps folder..but it does not works for me..
    i don't know why..i've try search for the solution and i think its about extend Plugin in java file..it should be CordovaPlugin for the latest version cordova being used. but its still not work when i change it..i'll very appreciate if you help me how to deal with it..im very new in this realm but i really need it friend..
    thank you so much.

    ReplyDelete
  5. could you send the demo for me ,please
    my email
    ne3ma.rayan91@gmail.com

    ReplyDelete
    Replies
    1. Hai Rayan, Can you check your mail , i sent it to you, Guys in my application i was used some older version of Phonegap Version, Right now i don't have laptop along with me as well as device, if i have laptop and device i will change according to current version, but don't worry, i think with this application you need to do less changes only.....

      Delete
  6. can u send me demo code to marthmadhu777@gmail.com

    ReplyDelete
  7. Hi i have got an alert that android intent is not able to send email
    why i am getting this alert n can u send me the code on my mail is sainikisha@gmail.com

    ReplyDelete
  8. Hi Konda Reddy,

    Such a nice article... Thanks for sharing your knowledge. It is working for me.. Thank you

    ReplyDelete
  9. Please send me a demo application

    ReplyDelete
  10. Hi Konda Reddy,
    It working for me, but i have a problem, how to attach multiple attachments?

    ReplyDelete
  11. Hi ,

    Can you send the demo application @ resham.mlk@gmail.com

    ReplyDelete
  12. Hi,
    I tried to integrate this code, I am using Cordova-2.4.0. I am getting an error in WebIntent.java - 'The method getContext() is undefined for the type CordovaInterface' .

    Please let me know if you a fix for this, or mail me a demo app to anupsveerapur@gmail.com.

    Thanks.

    ReplyDelete
  13. thanks for post but i having issue the same post
    can you plz send me demo example for send mail with attach.
    my email id is bougzalaamel@gmail.Com

    ReplyDelete
  14. hi m new to phone gap(android) thnks for post...m using cordova 3.0.0 ....i took your code and paste to simple hello world replace all the respective files...while build command it showing error type error cant read property'text'...null returned: 1...and not generating bin folder

    ReplyDelete
  15. my email id: rohitawana89@gmail.com
    if it is possible can send demo examle

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

    ReplyDelete
  17. Hi Can you tell me how to attach multiple attachments from the device ????

    ReplyDelete