android


Android send email with attachment via intent service


I'm trying to send an email from my applicayion.
this email sholud contain an attchment.
my MainActiviry calls to the intent service and looking for permissions. it's look like this -
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) )
startCommaSeparatedService();
else {
if(shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE) &&
shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE) )
Toast.makeText(this, "Track your nevi required access to external storage", Toast.LENGTH_LONG).show();
requestPermissions(PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
} else {
startCommaSeparatedService();
}
}
private void startCommaSeparatedService() {
ArrayList<ResultsExport> toExport = mDataBaseHelper.getAllDataParsed();
if(toExport.size() > 0) {
Intent intent = new Intent(MainActivity.this, CommaSeparatedValuesService.class);
intent.setAction(CommaSeparatedValuesService.ACTION_EXPORT_TO_MAIL);
intent.putParcelableArrayListExtra(CommaSeparatedValuesService.EXTRA_RESULT, toExport);
startService(intent);
} else
Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_results_to_export)
, Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_EXTERNAL_STORAGE)
if((grantResults[0] != PackageManager.PERMISSION_GRANTED) &&
(grantResults[1] != PackageManager.PERMISSION_GRANTED))
Toast.makeText(getApplicationContext(), "This application need permissions to external storage", Toast.LENGTH_LONG).show();
}
my CommaSeparatedValuesService looks like that -
package com.example.user.trackyournevi.services;
import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.Nullable;
import com.example.user.trackyournevi.bl.ResultsExport;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class CommaSeparatedValuesService extends IntentService{
public static final String ACTION_EXPORT_TO_MAIL = "com.example.user.trackyournevi.services.action.ACTION_EXPORT_TO_MAIL";
public static final String EXTRA_RESULT = "com.example.user.trackyournevi.services.extra.PARENT";
public static final String EXTRA_TRASHED = "com.example.user.trackyournevi.services.extra.TRASHED";
public static final String COMMA_DELIMITER = ",";
public static final String NEW_LINE_SEPERATOR = "\n";
public static final String CSV_FILE_HEADER = "Scan date" + COMMA_DELIMITER + "Organ" + COMMA_DELIMITER
+ "Side" + COMMA_DELIMITER + "Recommendation" + COMMA_DELIMITER + "Changes" + NEW_LINE_SEPERATOR;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public CommaSeparatedValuesService(String name) {
super(name);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
if(intent != null) {
final String action = intent.getAction();
if(ACTION_EXPORT_TO_MAIL.equals(action)) {
boolean trashed = intent.getBooleanExtra(EXTRA_TRASHED, false);
ArrayList<ResultsExport> results = intent.getParcelableArrayListExtra(EXTRA_RESULT);
handleActionExport(results, trashed);
}
}
}
public void handleActionExport(ArrayList<ResultsExport> results, boolean trashed) {
String path = null;
try {
path = writeToCSVFile(results);
} catch (IOException e) {
e.printStackTrace();
}
sentAttachedMail(path);
}
private static String writeToCSVFile(ArrayList<ResultsExport> results) throws IOException {
File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt");
patternDirectory.mkdirs();
FileOutputStream fos = null;
try {
fos = new FileOutputStream (new File(patternDirectory.getAbsolutePath().toString()), true); // true will be same as Context.MODE_APPEND
fos.write(CSV_FILE_HEADER.getBytes());
fos.write("\n".getBytes());
Iterator<ResultsExport> it = results.iterator();
while (it.hasNext()) {
ResultsExport r = it.next();
fos.write(r.getScanDate().getBytes());
fos.write(COMMA_DELIMITER.getBytes());
fos.write(r.getOrgan().toString().getBytes());
fos.write(COMMA_DELIMITER.getBytes());
fos.write(r.getSide().getBytes());
fos.write(COMMA_DELIMITER.getBytes());
fos.write(r.getRecommendation().getBytes());
fos.write(COMMA_DELIMITER.getBytes());
fos.write(r.getChanges().getBytes());
fos.write(NEW_LINE_SEPERATOR.getBytes());
fos.close();
}
} catch (FileNotFoundException e) {e.printStackTrace();}
return patternDirectory.getAbsolutePath().toString();
}
private void sentAttachedMail(String path) {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("text/plain");
email.putExtra(Intent.EXTRA_SUBJECT, "My Scannings");
email.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
email.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(Intent.createChooser(email , "Email:"));
}
}
Is someone can explain my whats worng in this code?
Tnx
Try this: Add setType and make sure your uri is not null
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("text/plain");
email.putExtra(Intent.EXTRA_SUBJECT, "My Scannings");
email.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
email.setType("message/rfc822");
startActivity(Intent.createChooser(email , "Email:"));

Related Links

Display integer value on TextView
How to fix Class Cast Exception While Casting List View to PullToRefreshListView in android
Generating PublicKey from Base64 encoded String
using google maps api in an android app
Showing error while trying to run mediaPlayer in AsyncTask
android design : fragment or view?
Clear all items in a ListFragment
Cocos2dx back key function not getting called
Am I allowed to use an open source Spritz clone in my app? [closed]
How to convert UIColor to Android color (packed int)?
how to set margins for an EditText inside an AlertDialog
Android add background behind imagebutton, edittext, imagebutton
Why the TextView gets truncated in a TableView and doesn´t fit the width of his TableRow parent?
how to pause a handler
Android Drag and Expand View
Take picture, saving picture and loading in imagview, error

Categories

HOME
localization
amp-html
pagination
themes
sitecore
package
socket.io
graphics
knitr
pdfbox
soa
hpc
pearson-correlation
tvos
google-admin-sdk
joomla3.0
sendgrid-api-v3
openpyxl
project-intu
filechannel
favicon
dynatrace
zerobrane
cumulocity
package-managers
package.json
asciidoctor-pdf
kendo-mobile
cgbitmapcontext
dataflow-diagram
pchart
object-storage
tosca
opentk
soot
datastax-enterprise-graph
jaws
mockjax
android-sugarorm
fossil
reverse
baidu-map
lubridate
alphabetical
news
mcustomscrollbar
azure-arm
levenshtein-distance
apriori
attributeerror
branching-and-merging
parser-generator
outputcache
apollostack
phpdbg
httrack
xbmc
textsum
term
jquery-ui-draggable
serde
wcftestclient
mschart
launchctl
podscms
java-bytecode-asm
android-testing
monkey
d3-force-directed
renaming
donations
cronexpression
usart
builtins
reporting-services-2012
spring-cloud-feign
dup
eigenvector
turbo-prolog
uiactionsheet
findfirst
user-management
vhosts
dllimport
lazybones
jdi
google-books
sha512
omnifaces
google-refine
node-serialport
zend-currency
fits
delayed-execution
rapidsvn
named-parameters
grails-plugin-rabbitmq
spring-remoting
amslidemenu
away3d
script#
flex++
uimanageddocument
zope.interface
stress
convention
node-redis
saxparseexception
umra
massive
objective-j
application-verifier
wcf-instancing
sifr3

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App