android exporting to csv and sending as email attachment
Thanks for everyone who tried to help..After taking a full day I have send an email from my app with attachment..This is the working code..
String columnString = "\"PersonName\",\"Gender\",\"Street1\",\"postOffice\",\"Age\"";
String dataString = "\"" + currentUser.userName +"\",\"" + currentUser.gender + "\",\"" + currentUser.street1 + "\",\"" + currentUser.postOFfice.toString()+ "\",\"" + currentUser.age.toString() + "\"";
String combinedString = columnString + "\n" + dataString;
File file = null;
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File dir = new File (root.getAbsolutePath() + "/PersonData");
dir.mkdirs();
file = new File(dir, "Data.csv");
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out.write(combinedString.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Uri u1 = null;
u1 = Uri.fromFile(file);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Person Details");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
Also If you have mounted your phone SDCard in the machine , this code wont work. Only one can access SDCard at one time. So in that case unmount your SDCard from computer and try..Thanks to the guy who answered here..Also make sure you have bought permission to write to external Storage in your manifest file...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Hope it helps someone...Thanks for everyone who tried to help..
How to send saved CSV file via email or upload with Google Drive in Android?
Create an xml file in res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--
name is the file name
path is the root of external storage, it means here: Environment.getExternalStorageDirectory()
-->
<external-path name="scale" path="."/>
<!--
another example: Environment.getExternalStorageDirectory() + File.separator + "temps" + "myFile.pdf"
-->
<external-path name="myFile" path="temps"/>
</paths>
add provider in your application tag in manifest
<!--android:name="android.support.v4.content.FileProvider"-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="your.application.package.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
Finally change your code to this:
public static void sendEmailWithAttachment(Context context) {
String filename="/scale.csv";
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
//Uri path = Uri.fromFile(filelocation);
Uri path = FileProvider.getUriForFile(context, "your.application.package.fileprovider", filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"email@gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Scale Data");
emailIntent.putExtra(Intent.EXTRA_TEXT, "This is the body");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
Some tips about defining file path from android docs
<files-path name="name" path="path" />
Represents Context.getFilesDir()
<cache-path name="name" path="path" />
Represents getCacheDir()
<external-path name="name" path="path" />
Represents Environment.getExternalStorageDirectory().
<external-cache-path name="name" path="path" />
Represents Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)
<external-media-path name="name" path="path" />
Represents Context.getExternalCacheDir().
Read more from docs
CSV file attachment gets not sending with email in Android
Try this in sendMail() instead of text/html
sendIntent.setType("text/csv ");
Not able to send .csv file with email in android
I got the solution for this problem.
Below are the solution
public boolean sendEmail() {
String destLocation = "";
String FILE = Environment.getExternalStorageDirectory()+"";
destLocation = FILE + "/" + Global.FILENAME;
boolean success = false;
Intent intentSendMail = new Intent(Intent.ACTION_SEND);
File mydir = getApplicationContext().getDir(Global.FOLDERNAME, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(mydir, Global.FILENAME);
copyFile(Uri.fromFile(fileWithinMyDir).toString(),destLocation);
if (!fileWithinMyDir.exists() || !fileWithinMyDir.canRead()) {
Toast.makeText(this, "Attachment Error", Toast.LENGTH_SHORT).show();
success = false;
} else {
intentSendMail.setType("application/csv");
intentSendMail.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+destLocation));
intentSendMail.putExtra(Intent.EXTRA_SUBJECT,
"Test Play file.");
intentSendMail.putExtra(Intent.EXTRA_TEXT, "");
startActivity(Intent.createChooser(intentSendMail, "E-mail"));
success = true;
}
return success;
}
Will anyone give example for sending mail with attachment in android
I got Working Code
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextTo);
textSubject = (EditText) findViewById(R.id.editTextSubject);
textMessage = (EditText) findViewById(R.id.editTextMessage);
buttonSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
String message = textMessage.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text");
File data = null;
try {
Date dateVal = new Date();
String filename = dateVal.toString();
data = File.createTempFile("Report", ".csv");
FileWriter out = (FileWriter) GenerateCsv.generateCsvFile(
data, "Name,Data1");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(data));
i.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(i, "E-mail"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public class GenerateCsv {
public static FileWriter generateCsvFile(File sFileName,String fileContent) {
FileWriter writer = null;
try {
writer = new FileWriter(sFileName);
writer.append(fileContent);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return writer;
}
}
Add this line in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-p
Related Topics
How to Use Dimens.Xml in Android
Could Not Access the Package Manager. Is the System Running While Installing Android Application
How to Send Notification to Specific Users with Fcm
What Are the Differences Among Internal Storage, External Storage, Sd Card and Removable Storage
Get the Last Picture Taken by User
Failed to Connect to Camera Service
Access Files from Assets/Www Directory
Can't Update Android Studio - Only Download
Action Buttons Doesn't Show Up on Action Bar
Android - Multi-Line Linear Layout
Cordova Android Requirements Failed: "Could Not Find an Installed Version of Gradle"
How to Tell Which App Was Selected by Intent.Createchooser
How to Get Bitmap from a Url in Android
Save State of Activity When Orientation Changes Android
How to Add Shadow to the Fab Provided with the Android Support Design Library