Getting "Parent directory of file is not writable" when trying to create a temp file. I am using Eclipse and the emulator. I am using the permission in my Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Here is the code:
#SuppressWarnings("static-access")
public void sendEmail() {
Calendar today = new GregorianCalendar();
Log.d(TAG, "Path:" + Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/GPSTracking/" + MakeTextDate(today) + ".csv");
File tempFile = null;
try {
tempFile.createTempFile(MakeTextDate(today), ".csv");
FileWriter out = FormatEmail(tempFile);
}
catch (IOException e) {
// error
Log.d(TAG, "create temp file:" + e.toString());
}
try {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Trip report");
emailIntent
.putExtra(Intent.EXTRA_TEXT, "Here is your Trips Report");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
emailIntent.setType("plain/text");
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (Exception e) {
e.printStackTrace();
}
}
You're trying to create file in root directory of storage, not sd-card
tempFile.createTempFile(MakeTextDate(today), ".csv");
Create file as you writing log with full path to external storage.
Related
I'm developing an android app in which i'll be generating an pdf file which i want to sent as an email. Following is the code for generating pdf file:
public void createPDF(View view) {
Document doc = new Document();
String outPath = Environment.getExternalStorageDirectory()+"/mypdf.pdf";
try {
PdfWriter.getInstance(doc,new FileOutputStream(outPath));
doc.open();
doc.add(new Paragraph(edttxt1.getText().toString()));
doc.add(new Paragraph(txt.getText().toString()));
doc.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Help me to email this file by clicking a button.
you can see more details here: How to send an email with a file attachment in Android
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, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "body text");
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "/mypdf.pdf";
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"));
I am currently looking for a way to save a file in the internal memory of my device, and then to send it by mail. For this, I use FileProvider
So on the Android Manifest, I add those lines in my manifest :
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="exploration.syte.fr.sendbymail4.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/paths" />
</provider>
And on res/xml path I added this file path : paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="files/"/>
</paths>
Here is the code I use to create my file - a really simple text file that contains the word "test".
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String textToWrite = "test";
try {
File path = this.getFilesDir();
File file = new File(path, "myfile.txt");
String chemin = file.getAbsolutePath().toString();
Log.i("MainActivity", chemin);
Toast.makeText(this, chemin, Toast.LENGTH_LONG).show();
FileOutputStream fos = new FileOutputStream(file);
fos.write(textToWrite.getBytes());
fos.close();
//Toast.makeText(this, "File correctly saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.d("Main", "Exception", e);
}
try {
sendFile(this);
} catch (Exception e) {
Log.d("Main", "Exception", e);
}
}
And the code I use to send the file via e-mail
public static void sendFile(Context context){
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String directory=(String.valueOf(context.getFilesDir())/*+File.separator+"directory"*/);
File file=new File(directory+File.separator+"myfile.txt");
Uri uri = FileProvider.getUriForFile(context, "exploration.syte.fr.sendbymail4.fileprovider", file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
}
**The problems that i am currently encoutering are : **
My file is not save in the correct directory : it is save on /data/user/0/exploration.syte.fr.sendbymail4/files/myfile.txt
And I want my file to be save on : /data/data/exploration.syte.fr.sendbymail4/files/myfile.txt
How can I set the path were the file is save correctly ?
Thanks in advance !
I will save the image
public static String saveImage(Context context, Bitmap finalBitmap) {
String root = context.getFilesDir().getAbsolutePath();
// String root = context.getCacheDir().getAbsolutePath();
File myDir = new File(root + subFolder);
if (!myDir.exists()) {
myDir.mkdirs();
}
File file = new File(myDir, dateFilenameFormat.format(new Date()) + ".jpg");
try {
FileOutputStream out = new FileOutputStream(file);
downScale(finalBitmap).compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
return file.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
file_provider_paths.xml
<paths>
<cache-path name="cache" path="/" />
<files-path name="files" path="/" />
</paths>
And send (work for getFilesDir or getFilesDir from "cache" or "files" dirs)
public static void sendEmail(String attachmentFile, String message, Context context) {
try {
String email = "myname#gmail.com";
String subject = "subject";
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
File file = new File(attachmentFile);
Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(android.content.Intent.EXTRA_TEXT, message);
context.startActivity(Intent.createChooser(intent, "Sending email..."));
/*
PackageManager pm = context.getPackageManager();
if (intent.resolveActivity(pm) != null) {
context.startActivity(Intent.createChooser(intent, "Sending email..."));
}
*/
} catch (Throwable t) {
Log.d(TAG, t.getLocalizedMessage());
}
}
I am trying to send an email with attachment from my android app. But the email somehow goes out without the attachment, even though the file exists. In the email sending view, it shows the attachment (with file size even), but after sending, on the receiver side, there is no attachment. Any idea why?
private void copyFileToExternal() throws IOException {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "data/com.dw.inspectionhelperNSTC/databases/Inspection.db";
String backupDBPath = "Inspection_backup.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB)
.getChannel();
FileChannel dst = new FileOutputStream(backupDB)
.getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), "testing", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "not exist", Toast.LENGTH_LONG).show();
System.out.println("currentDB does not exists");
}
} else {
Toast.makeText(MainActivity.this,
"NO SDcard so unable to send the database backup",
Toast.LENGTH_SHORT).show();
System.out.println("sdcard cant write");
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_LONG).show();
System.out.println("exception" + e.getLocalizedMessage());
}
}
private void sendEmail(String email) {
ArrayList<Uri> uris = new ArrayList<Uri>();
// Adding the inspection DB;
File file = new File(Environment.getExternalStorageDirectory(),
"Inspection_backup.db");
Uri path = Uri.fromFile(file);
uris.add(path);
// Adding the stacttrack file with uncaught expection
File file2 = new File(Environment.getExternalStorageDirectory(),
Constant.STACKTRACE_FILE);
Uri path2 = Uri.fromFile(file2);
uris.add(path2);
Intent intent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
intent.setType("application/octet-stream");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"inspection database");
String to[] = { email };
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.putExtra(Intent.EXTRA_TEXT,
"sending inspection database for reporting");
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivityForResult(Intent.createChooser(intent, "Send mail..."),
1222);
}
public void sendMailWithIntent(String emailTo,
String subject, String emailText, List<String> filePaths) {
try {
//need to "send multiple" to get more than one attachment
final Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
Util.extractEmails(emailTo));
// emailIntent.putExtra(android.content.Intent.EXTRA_CC,
// new String[]{emailCC});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);
ArrayList<Uri> uris = new ArrayList<Uri>();
//has to be an ArrayList
if (filePaths != null) {
//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);
Intent chooser = Intent.createChooser(emailIntent, "Send mail...");
activity.startActivityForResult(chooser, 1);
} catch (Exception e) {
new ShowToast(context, e.getMessage());
}
}
Call it like
List<String> list = new ArrayList<>();
list.add(TO_ATTACH_ONE);
list.add(TO_ATTACH_TWO);
sendMailTest.sendMailWithIntent(toAddresses, subject, body, list);
private void sendEmail(String filename)
{
String filePath=Environment.getExternalStorageDirectory().toString()+ File.separator+ folderName +File.separator+ filename;
File file = new File(filePath);
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.setType("*/*");
i.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
i.putExtra(Intent.EXTRA_TEXT , "Body");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "No Email Found", 5000);
}
}
I hope it will help you out.
public void onClick(View arg0) {
String fname1 = text_fname.getText().toString();
String fname2 = edit_fname.getText().toString();
String lname1 = text_lname.getText().toString();
String lname2 = edit_lname.getText().toString();
String space = "\t";
String newLine = "\n";
File file = null;
FileOutputStream fos = null;
try {
file = getActivity().getFilesDir();
fos = getActivity().openFileOutput("test.xls", Context.MODE_PRIVATE);
fos.write(fname1.getBytes());
fos.write(space.getBytes());
fos.write(fname2.getBytes());
fos.write(newLine.getBytes());
fos.write(lname1.getBytes());
fos.write(space.getBytes());
fos.write(lname2.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(getActivity(), "File saved in " + file, Toast.LENGTH_LONG).show();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
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");
startActivity(Intent.createChooser(i, "Send mail..."));
}
On the click of the button, I'm creating a "test.xls" file with strings inside and also calling this:
Here's the output after clicking gmail:
My questions is, how can I attach "test.xls" file in my email? So i can send it to whoever recipient I'd like.
File file = new File(Environment.getExternalStorageState()+"/folderName/test.xls");
Uri path = Uri.fromFile(file);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("application/octet-stream");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
String to[] = { email };
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.putExtra(Intent.EXTRA_STREAM, path);
startActivityForResult(Intent.createChooser(intent, "Send mail..."),
1222);
Add the following line to your Intent.
String PATH="Full path of the File that you want to send" ;
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(PATH));
Use below code.
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/octet-stream");
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(), "/folder_name/file_name"));
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
emailIntent.setType("text/plain");
startActivity(emailIntent);
Try this approach, in your project create EmailActivity.java class and paste this code..
package com.app.yourpackegename;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
public class EmailActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// to send data.xls stored in Root of SDCARD
// Environment.getExternalStorageState() returns location of sdcard
String fullFilePath = Environment.getExternalStorageState()+ "/data.xls";
String email = "you#yourdomain,com";
String subject = "email subject";
String message = "custome message string";
File file = new File(fullFilePath);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("application/octet-stream");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
String to[] = { email };
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.putExtra(Intent.EXTRA_STREAM, path);
int requestCode = 1000;
startActivityForResult(
Intent.createChooser(intent, "Send mail via..."), requestCode);
}
}
Hope this helps you. let me know :)
I am creating a file and then sending it as attachment mail in background from my app.All is working fine mail sending is done successfully but issue is here that while creating file i named it as abc.csv and it file stored in dir with this name but when i got the attachment then it is named as <<_mnt_sdcard_MyTest_abc.csv>>. Here is the code which i am using to get the attachment.
private boolean SendMail() {
boolean result=false;
txtAdd=(EditText)findViewById(R.id.txtAdd);
File folder;
folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ getString(R.string.app_name));
boolean var = false;
if (!folder.exists())
var = folder.mkdir();
Mail m = new Mail("abc#gmail.com", "*****");
//String[] toArr = {EmailFetcher.getEmail(this)};
String[] toArr = {txtAdd.getText().toString()};
m.setTo(toArr);
m.setFrom("abc#gmail.com");
m.setSubject("XXXXXXXXX");
m.setBody("XXXXXXXXXXXXXX");
try {
m.addAttachment(folder+"/abc.csv");
if(m.send()) {
result= true;
} else {
result= false;
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return result;
}
How to set the file name in attachment.
Just use this it`s work for me.
public void sendImageInEmail(String filePath)
{
try
{
String html = "<html><body><center>Created By ZalaJanakSinh<center></body></html>";
String address = "";
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ address });
email.putExtra(Intent.EXTRA_SUBJECT, "Created By Zala JanakSinh");
//need this to prompts email client only
email.setType("text/html");
email.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(html));
email.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
email.setType("image/*");
email.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath)));
myContext.startActivity(Intent.createChooser(email, "Choose an Email client :"));
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Error in SendImageInEmail==>"+e.toString());
}
best of Luck Dear