I have a HTML string which I want to attach to mail as a file. I could save this string to a file and attach it but I want to do it without saving it to a file. I think it should be possible but I don't know how to do it. This is my code:
String html = "<html><body><b><bold</b><u>underline</u></body></html>";
Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(html));
// this is where I want to create attachment
intent.putExtra(Intent.EXTRA_STREAM, Html.fromHtml(html));
startActivity(Intent.createChooser(intent, "Send Email"));
How can I attach string as a file to mail?
This code saves you from adding a manifest uses permission to read from external sd card. It creates a temp in files directory on your app private directory then creates the file with the contents of your string and allows read permission so that it can be accessed.
String phoneDesc = "content string to send as attachment";
FileOutputStream fos = null;
try {
fos = openFileOutput("tempFile", Context.MODE_WORLD_READABLE);
fos.write(phoneDesc.getBytes(),0,phoneDesc.getBytes().length);
fos.flush();
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
if (fos != null)try {fos.close();} catch (IOException ie) {ie.printStackTrace();}
}
File tempFBDataFile = new File(getFilesDir(),"tempFile");
Intent emailClient = new Intent(Intent.ACTION_SENDTO, Uri.parse("someone#somewhere.com"));
emailClient.putExtra(Intent.EXTRA_SUBJECT, "Sample Subject";
emailClient.putExtra(Intent.EXTRA_TEXT, "Sample mail body content");
emailClient.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFBDataFile));//attachment
Intent emailChooser = Intent.createChooser(emailClient, "select email client");
startActivity(emailChooser);
This should be called whenever you dont need the file anymore.
File tempData = new File(getFilesDir(),"tempFile");
if (tempData.exists()) {
tempData.delete();
}
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"));
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("png/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {
"mail--id" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
Uri uri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "/saved_images/MyImage.png"));
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
emailIntent.setType("text/plain");
startActivity(emailIntent);
and don't forget to add this below permission in manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" /
Related
I want to share a file made and written using Service via email. I know I can't share a private file with email but how to use the content provider to do that. I read online that content Provider can help but I can't make it work. (I merged file creation code together with intent creation for simplicity)
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ "someone#gmail.com"});
email.putExtra(Intent.EXTRA_SUBJECT, "Nothing");
email.putExtra(Intent.EXTRA_TEXT, "Nothing");
email.setType("message/rfc822");
Uri uri = null;
try {
File file = new File(this.getExternalFilesDir(null), "samplefile.txt");
uri = FileProvider.getUriForFile(this, "lcukerd.com.android.fileprovider", file);
FileOutputStream osw = new FileOutputStream(file);
osw.write("Say something".getBytes("UTF-8"));
osw.close();
Log.i("File Reading stuff", "success");
} catch (Exception e)
{
Log.e(tag,"File creation error",e);
}
//Uri uri = FileProvider.getUriForFile(this, "lcukerd.com.android.fileprovider", );
//Uri uri = Uri.fromFile(getFileStreamPath("samplefile.txt"));
Log.d(tag,uri.toString());
email.putExtra(Intent.EXTRA_STREAM,uri);
startActivityForResult(Intent.createChooser(email, "Choose an Email client :"),1);
I get option to choose app but then nothing happens. Gmail app does not open.
Gmail opens if I use Uri uri = Uri.fromFile(getFileStreamPath("samplefile.txt")); but then I get "permission denied for attachment".
Actually, I want to write file from service then send that file via email. Pls help me achieve that.
Use the following code,
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("*/*");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"me#gmail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Test Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"go on read the emails");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromfile(new File(yourtextfilepath));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Make sure that your text file path should be from external memory card. Action send wont accept the files from internal memory.
Also try this also,
Link 1
I am trying to attach a pdf file in gmail app. I have read this and this (applied solution) I am trying as;
public static void attachFile(Context ctx) {
String TAG = "Attach";
File documentsPath = new File(ctx.getFilesDir(), "documents");
Log.i(TAG,"documentsAbsolutePath Output");
Log.i(TAG, documentsPath.getAbsolutePath().toString());
File file = new File(documentsPath, "sample.pdf");
if ( file.exists() ) {
Toast.makeText(ctx, "Exits", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(ctx, "Not Exist", Toast.LENGTH_LONG).show();
}
Log.i(TAG,"file Output");
Log.i(TAG, file.toString());
Log.i(TAG, String.valueOf(file.length()));
Uri uri = FileProvider.getUriForFile(ctx, "com.example.fyp_awais.attachfiletest2.fileprovider", file);
Log.i(TAG,"URI Output");
Log.i(TAG,uri.toString());
Intent intent = ShareCompat.IntentBuilder.from((Activity) ctx)
.setType("application/pdf")
.setStream(uri)
.setChooserTitle("Choose bar")
.createChooserIntent()
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ctx.startActivity(intent);
}
Outputs
documentsAbsolutePath Output
/data/data/com.example.fyp_awais.attachfiletest2/files/documents
file Output
/data/data/com.example.fyp_awais.attachfiletest2/files/documents/sample.pdf
0
URI Output
content://com.example.fyp_awais.attachfiletest2.fileprovider/pdf_folder/sample.pdf
Menifest
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.fyp_awais.attachfiletest2.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepath" />
</provider>
FilePath.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="pdf_folder" path="documents/"/>
</paths>
</PreferenceScreen
A pdf file is saved in Galaxy Core Prime\Phone\documents. (file size: 53.7KB)
But it gives
Cannot attach empty file.
I am confused with folder-name in this line <files-path name="pdf_folder" path="documents/"/>. The file is in the \Phone\documents. Then why folder name?
Edit 1
Tried to replace setType(application/pdf) with setType("message/rfc822") But did not work. Any help?
Send the file in URI format like this:
Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("application/image");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
ArrayList<Uri> uris = new ArrayList<>();
//convert from paths to Android friendly Parcelable Uri's
uris.add(frontImageUri);
uris.add(backImageUri);
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
if it's ok To send Zip then try this way
String fileNameStor_zip = Environment.getExternalStorageDirectory() + "/" + fileName + ".zip";
String[] path = { your 1st pdf File Path, your 2nd pdf File Path};
Compress compress = new Compress(path, fileNameStor_zip);
compress.zip();
URI = Uri.parse("file://" + fileNameStor_zip);
Provide your Gmail Intent
intent.putExtra(Intent.EXTRA_STREAM, URI);
Uri contentUri = FileProvider.getUriForFile(this, "com.mydomain.fileprovider", newFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
i.setData(contentUri);
String filename="my_file.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 attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(emailIntent , "Send email..."));
You have to grant the permission to access storage for gmail.
In case it helps- here's what I do in an app debug function with a few files, it shouldn't really be any different.
I do copy/export them into a user-public folder first before attaching them, and make them world readable.
if (verifyStoragePermissions(c)) {
final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"recipient#email.address"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
//build up message
ArrayList<Uri> uris = new ArrayList<>();
StringBuilder content = new StringBuilder();
content.append(
String.format(
c.getString(R.string.message_log_upload_email_body) +
"\n\nmodelDesc:%s \n\nmanuf:%s \n\naId: %s,\n\nhIid: %s,\n\nfbId: %s.",
Build.MODEL, Build.MANUFACTURER, getSomeVar1(), getSomeVar2(), getSomeVar3())
);
content.append("\n\nMy logged in account id is: ").append(getAccountId(c)).append(".");
content.append("\n\nHere's an overview of my attachments:\n");
for (String s : addresses) {
File f = new File(s);
//noinspection ResultOfMethodCallIgnored
f.setReadable(true, false);
Uri add = Uri.fromFile(f);
//add attachment manifest
content.append(String.format(Locale.UK, "|-> %s (%.3f kb)\n", f.getName(), (float) f.length() / 1024));
uris.add(add);
}
//attach the things
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
//set content/message
intent.putExtra(Intent.EXTRA_TEXT, content.toString());
c.startActivity(intent);
}
}
addresses is a String[] param to that function. I build it up by making the functions I use to export the files return arrays of strings of the addresses of the files they've exported - as I initially store the files in my app's private storage
I wish to implement a button that upon pressing it will open the default email client with an attachment file.
I am following this, but am getting an error message on the startActivity, saying it is expecting an activity param while I am giving it an intent.
I am using API 21 and Android Studio 1.1.0, so perhaps it has something to do with the comment in the answer provided in the link?
This is my fourth day as Android developer so sorry if I am missing something really basic.
Here is my code:
public void sendFileToEmail(File f){
String subject = "Lap times";
ArrayList<Uri> attachments = new ArrayList<Uri>();
attachments.add(Uri.fromFile(f));
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachments);
intent.setClassName("com.android.email", "com.android.mail.compose.ComposeActivity");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
Official documentation with Kotlin snippets is here: https://developer.android.com/guide/components/intents-common#ComposeEmail
I think your problem is that you are not using the correct file path.
The following works for me:
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"email#example.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
emailIntent.putExtra(Intent.EXTRA_TEXT, "body text");
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "temp/attachement.xml";
File file = new File(root, pathToMyAttachedFile);
if (!file.exists() || !file.canRead()) {
return;
}
Uri uri = Uri.fromFile(file);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));
EDIT: Requesting access to storage just to share a file private to your app is probably not a good idea. Fortunately, after a little configuration, it's very easy to share a file from your app private storage. See this guide: https://developer.android.com/training/secure-file-sharing/setup-sharing
If you share a file that is on external storage, you also need to give the user permission via a manifest file like below
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For newer devices you will encounter FileUriExposedException. Here is how to avoid it in Kotlin.
val file = File(Environment.getExternalStorageDirectory(), "this")
val authority = context.packageName + ".provider"
val uri = FileProvider.getUriForFile(context, authority, file)
val emailIntent = createEmailIntent(uri)
startActivity(Intent.createChooser(emailIntent, "Send email..."))
private fun createEmailIntent(attachmentUri: Uri): Intent {
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.type = "vnd.android.cursor.dir/email"
val to = arrayOf("some#email.com")
emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri)
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject")
return emailIntent
}
Try to use this.It is working...
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("*/*");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(listVideos.get(position).getVideoPath())));//path of video
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Thanks
I have to following problem:
I want to send an email with an image attached to it.
I wrote this code:
File file = context.getDir("Files", context.MODE_WORLD_WRITEABLE);
File image = new File(file, "image.jpg");
Uri U = Uri.fromFile(image);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/jpg");
i.putExtra(Intent.EXTRA_STREAM, U);
context.startActivity(Intent.createChooser(i, "Email:"));
The email is sent but there is no attachment.
Does anybody have any idea why the email is sent without the attachment?
EDIT
I have found the answer to my question. Because the image was stored on the internal storage, it did not have enough rights so it could not be sent via email. I've moved my image to externalStorage and now it's working :)
Thanks,
Ark
String smsBody = "Body of the Content";
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("image/*");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] { "" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Subject of the Mail");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, smsBody);
emailIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile("mnt/sdCard/SampleImageFloder/TestImage.png"));
emailIntent.setType("vnd.android.cursor.dir/email");
activity.startActivity(Intent.createChooser(emailIntent,"Email:"));
Try this one -
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[]{"email"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,"Test");
//has to be an ArrayList
ArrayList<Uri> uris = new ArrayList<Uri>();
//convert from paths to Android friendly Parcelable Uri's
for (String file : filePaths)
{
File fileIn = new File(file);
Uri u = Uri.fromFile(fileIn);
uris.add(u);
}
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
context.startActivity(emailIntent);
Just see my Existing Answer also
I am sending mail through my application.
For that I am using 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 work fine but i want to attach an xml file with it.
Is it possible? How?
There are lots of similar questions asked with perfect solution in Stack Overflow already.
You can have look to few : here and here and here
Solution is to use with email intent : one more putExtra with Key-Extra_Stream and Value-uri to file.
And please go through the FAQ to undersatand How to better benifit from the site.
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"));
ACTION_SEND_MULTIPLE should be the action and then emailIntent.setType("text/plain"); followed by:
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);
For sending an attachment with gmail:
File should be on External storage device or created in External storage device
For that you need to add the following to Android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
get External path by
String pathname= Environment.getExternalStorageDirectory().getAbsolutePath();
Create a new file by
File myfile=new File(pathname,filename);
Write to file based on whatever logic you are applying
Now the Intent
Intent email=new Intent(android.content.Intent.ACTION_SEND);
email.setType("plain/text");
Put Extras
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 Activity
startActivity(Intent.createChooser(email, "E-mail"));