Monday, December 22, 2014

Send Attachment With E-Mail in Android

activity_attachment.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Send Mail" />

</RelativeLayout>

AttachmentActivity.java


public class AttachmentActivity extends Activity {

Bitmap myBitmap;
Button b_sendMail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attachment);
     
        b_sendMail = (Button)findViewById(R.id.button1);
        b_sendMail.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DowloadImageFromServer dowloadImageFromServer =
                            new DowloadImageFromServer();
             dowloadImageFromServer.execute();
}
});
     
  }
 
class DowloadImageFromServer extends AsyncTask<String, Integer, String>
{
     private ProgressDialog pd;

     @Override
     protected String doInBackground(String... arg0) {
      // TODO Auto-generated method stub

       try {
     
          URL url = new URL("http://www.gstatic.com/webp/gallery/1.jpg");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       connection.setDoInput(true);
  connection.connect();
  InputStream input = connection.getInputStream();
          myBitmap = BitmapFactory.decodeStream(input);
       } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return null;
   }

     @Override
     protected void onPostExecute(String result) {
         // TODO Auto-generated method stub
         super.onPostExecute(result);

          pd.dismiss();

         File myDir = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/aa_sample_gmail");  
         boolean chack= myDir.mkdirs();

        String fname = "sample.jpg";
        File file = new File (myDir, fname);
        if (file.exists ()) file.delete ();
        try{
            FileOutputStream out = new FileOutputStream(file);
      myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
      out.close();
        }
          catch (Exception e)
        {
        e.printStackTrace();
      }

      String description_test = "Sample Description";
      final Intent emailIntent = new Intent( android.content.Intent.ACTION_SEND);
      emailIntent.setType("image/jpeg");
      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                              new String[] { "aditmicrosys1@gmail.com" });
      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"MOC");
      emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,description_test);

      // send Image on gmail from SD Card
      String path = Images.Media.insertImage(getContentResolver(), myBitmap,
                                    "Sample Mail", null);
      Uri screenshotUri = Uri.parse(path);
      emailIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);

      final PackageManager pm = AttachmentActivity.this.getPackageManager();
      final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
      ResolveInfo best = null;
      for(final ResolveInfo info : matches){
       
         if(info.activityInfo.packageName.toLowerCase().contains("gmail") ||                              info.activityInfo.name.toLowerCase().contains("gmail"))
         best = info;
      }
   
      if (best != null)
         emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
         startActivity(Intent.createChooser(emailIntent, "Send mail..."));
      }

    @Override
    protected void onPreExecute() {
     // TODO Auto-generated method stub
     super.onPreExecute();

     pd = new ProgressDialog(AttachmentActivity.this);
     pd.setMessage("Please wait....");
     pd.setCancelable(false);
     pd.show();
     }
    }
}

Give Following permissions in manifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

No comments:

Post a Comment