How to send an email with a file attachment in Android
Use the below code to send a file within a email.
String filename="contacts_sid.vcf"; File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);Uri path = Uri.fromFile(filelocation); Intent emailIntent = new Intent(Intent.ACTION_SEND);// set the type to 'email'emailIntent .setType("vnd.android.cursor.dir/email");String to[] = {"asd@gmail.com"};emailIntent .putExtra(Intent.EXTRA_EMAIL, to);// the attachmentemailIntent .putExtra(Intent.EXTRA_STREAM, path);// the mail subjectemailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");startActivity(Intent.createChooser(emailIntent , "Send email..."));
Folder_name is the name of the file in the Internal Storage of your phone. (ACTUALLY EXTERNAL_STORAGE).file_name is the name of the file you want to send.
private void ShareViaEmail(String folder_name, String file_name) { try { File root= Environment.getExternalStorageDirectory(); String filelocation= root.getAbsolutePath() + folder_name + "/" + file_name; Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setType("text/plain"); String message="File to be shared is " + file_name + "."; intent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse( "file://"+filelocation)); intent.putExtra(Intent.EXTRA_TEXT, message); intent.setData(Uri.parse("mailto:xyz@gmail.com")); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } catch(Exception e) { System.out.println("is exception raises during sending mail"+e); }}
The example on the official Android site worked for me.All what is need it to add the
startActivity(Intent.createChooser(emailIntent , "Send email..."));
as done in Agarwal's answer