How to attach files with sending mail in the Android application?

I send mail through my application. For this, I use the following code.

Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL , new String[]{" recipient@example.com "}); i.putExtra(Intent.EXTRA_SUBJECT, "subject of email"); i.putExtra(Intent.EXTRA_TEXT , "body of email"); try { startActivity(Intent.createChooser(i, "Send mail...")); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show(); } 

It just works fine, but I want to attach an xml file to it. Is it possible? How?

+4
source share
4 answers

There are already many similar questions with the perfect solution in Stack Overflow.

You can look at some of them: here and here and here

The solution should be used with email intent: another putExtra with Key-Extra_Stream and Value-uri for the file .

And please go to the subscript FAQ and how best to benefit from the site.

+5
source
 String pathname= Environment.getExternalStorageDirectory().getAbsolutePath(); String filename="/MyFiles/mysdfile.txt"; File file=new File(pathname, filename); Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_SUBJECT, "Title"); i.putExtra(Intent.EXTRA_TEXT, "Content"); i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); i.setType("text/plain"); startActivity(Intent.createChooser(i, "Your email id")); 
+3
source

ACTION_SEND_MULTIPLE must be an action and then emailIntent.setType("text/plain"); , and then:

 ArrayList<Uri> uris = new ArrayList<Uri>(); String[] filePaths = new String[] {"sdcard/sample.png", "sdcard/sample.png"}; for (String file : filePaths) { File fileIn = new File(file); Uri u = Uri.fromFile(fileIn); uris.add(u); } emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); startActivity(emailIntent); 
0
source

To send attachments with gmail:

  • The file must be on an external storage device or created on an external storage device

    • To do this, you need to add the following to Android Manifest <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    • get the outer path

      String pathname= Environment.getExternalStorageDirectory().getAbsolutePath();

    • Create a new file

      File myfile=new File(pathname,filename);

    • Writing to a file based on any logic that you apply.
    • Now the intention

      Intent email=new Intent(android.content.Intent.ACTION_SEND);

      email.setType("plain/text");

    • Put extra features

      email.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(myfile)); email.putExtra(Intent.EXTRA_SUBJECT, "my email subject"); email.putExtra(Intent.EXTRA_TEXT, "my email text");

    • Start of activity startActivity(Intent.createChooser(email, "E-mail"));

0
source

Source: https://habr.com/ru/post/1398610/


All Articles