((HomeActivity) getActivity()).contactus
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendEmail();
}
});
((HomeActivity) getActivity()).attachmentimageview
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
MY_INTENT_CLICK);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == MY_INTENT_CLICK) {
if (null == data)
return;
String selectedImagePath;
Uri selectedImageUri = data.getData();
// MEDIA GALLERY
selectedImagePath = ImageFilePath.getPath(
getActivity(), selectedImageUri);
Log.i("Image File Path", "" + selectedImagePath);
// txta.setText("File Path : \n" + selectedImagePath);
}
}
}
private void sendEmail() {
try {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String[] recipients = new String[] { "Enter email" };
emailIntent
.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
emailIntent
.putExtra(
Intent.EXTRA_EMAIL,
new String[] { "anilkumar#softageindia.com,danyalozair#gmail.com" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Feedback");
emailIntent.putExtra(Intent.EXTRA_STREAM, selectedImagePath );
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
Html.fromHtml(""));
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "HI"
+ "\n\n" + contactustext.getText().toString());
emailIntent.setType("message/rfc822");
startActivity(emailIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
This is my code i want to attach file from Sd card or gallery i am using given code i am able to get path from galley But when i click on contact Us Button then it same work to get file directory if we not use attachment then it work properly with text please check where am doing wrong and how to fix it please suggest me actully i want send some text and also with attachment send via gmail when i click on button contact us it redirect to attachment and text to gmail then we can send it .
you can attach file as :
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Please find attachment");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+"you file's path"));
startActivity(Intent.createChooser(sharingIntent, "Attach using..."));
Firstly, create this method in your Activity or Fragment outside of onCreate
public static void getVcardString() {
String path = null;
String vfile = null;
vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, null);
phones.moveToFirst();
Log.i("Number of contacts", "cursorCount" +phones.getCount());
for(int i =0;i<phones.getCount();i++) {
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.i("lookupKey", " " +lookupKey);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
filevcf = new File(path);
Log.i("file", "file" +filevcf);
}catch(Exception e1) {
e1.printStackTrace();
}
}
Log.i("TAG", "No Contacts in Your Phone");
}
and call it inside onCreate like:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getVcardString();
}
And now again, create a new method to send Email outside of onCreate like :
protected void data() {
File filelocation = filevcf ;
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.setType("application/x-vcard");
sharingIntent.putExtra(Intent.EXTRA_EMAIL, "mail#gmail.com" );
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+filelocation.getAbsolutePath()));
startActivity(Intent.createChooser(sharingIntent, "Send email"));
}
And call this data() method onClick of your send email button like :
data();
Please let me know if you get any problem now.
Related
I am attaching a TEXT file to Email with code :
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
"abc#gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report");
emailIntent.putExtra(Intent.EXTRA_TEXT, prepareBodyMail());
File root = Environment.getExternalStorageDirectory();
File file = new File(root, "/MyFolder/report.txt");
Uri uri = Uri.fromFile(file);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));
This code works perfectly with Gmail, Email and other apps
But this is not attaching file with INBOX application by Google
Only Body and subject are coming without any attachment
I have reported this problem to Google Groups at Inbox Problem
Can anybody help what I am missing in code?
String fileLocation = Environment.getExternalStorageDirectory() + "/MyFolder/report.txt";
String to[] = {"abc#gmail.com"};
Intent intentEmail = new Intent(Intent.ACTION_SEND);
intentEmail.setType("vnd.android.cursor.dir/email");
intentEmail.putExtra(Intent.EXTRA_EMAIL, to);
intentEmail.putExtra(Intent.EXTRA_STREAM, fileLocation);
intentEmail.putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(intentEmail , "Pick an Email provider"));
Try this
Uri myUri = Uri.parse("file://" + path);
emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"email#example.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
intent.putExtra(Intent.EXTRA_TEXT, "body text");
File root = Environment.getExternalStorageDirectory();
File file = new File(root, xmlFilename);
if (!file.exists() || !file.canRead()) {
Toast.makeText(this, "Attachment Error", Toast.LENGTH_SHORT).show();
finish();
return;
}
Uri uri = Uri.fromFile("file://" + file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Send email..."));
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 method
List<String> list = new ArrayList<>();
list.add(TO_ATTACH_ONE);
list.add(TO_ATTACH_TWO);
sendMailWithIntent(toAddresses, subject, body, list);
It looks like that ACTION_SENDTO doesn't support attachments officially. It works only for Gmail and default email client because they use "undocumented" feature. The only way I found to send emails with attachments is to use ACTION_SEND instead.
My solution:
public class EmailSender {
private static final String INTENT_DATA_SCHEME_EMAIL = "mailto:";
private static final String FILE_PROVIDER_AUTHORIZER = "com.smartinhalerlive.app.fileprovider";
private String subject;
private String body;
private File attachment;
public EmailSender(String subject, String body, File attachment) {
this.subject = subject;
this.body = body;
this.attachment = attachment;
}
public void sendEmail(Context context, EmailSenderListener listener) {
List<ResolveInfo> emailClients = getEmailClients(context);
if (null != emailClients) {
ResolveInfo defaultEmailClient = getDefaultEmailClient(emailClients);
if (null != defaultEmailClient) {
sendEmailUsingSelectedEmailClient(context, defaultEmailClient, listener);
} else {
showSelectEmailClientsDialog(context, emailClients, listener);
}
}
}
private void showSelectEmailClientsDialog(Context context,
List<ResolveInfo> emailClients,
EmailSenderListener listener) {
String[] emailClientNames = getEmailClientNames(context, emailClients);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.email_dialog_title);
builder.setItems(emailClientNames, (dialog, which) -> {
sendEmailUsingSelectedEmailClient(context, emailClients.get(which), listener);
}
);
builder.create().show();
}
#NonNull
private static String[] getEmailClientNames(Context context, List<ResolveInfo> emailClients) {
PackageManager packageManager = context.getPackageManager();
String[] emailClientNames = new String[emailClients.size()];
for (int i = 0; i < emailClients.size(); i++) {
emailClientNames[i] = emailClients.get(i).activityInfo.applicationInfo.loadLabel(packageManager).toString();
}
return emailClientNames;
}
#Nullable
private static ResolveInfo getDefaultEmailClient(List<ResolveInfo> emailClients) {
ResolveInfo defaultEmailClient = null;
if (emailClients.size() == 1) {
defaultEmailClient = emailClients.get(0);
} else {
for (ResolveInfo emailClient : emailClients) {
if (emailClient.isDefault) {
defaultEmailClient = emailClient;
break;
}
}
}
return defaultEmailClient;
}
private static List<ResolveInfo> getEmailClients(Context context) {
PackageManager pm = context.getPackageManager();
Intent emailDummyIntent = getEmptyEmailIntent();
return pm.queryIntentActivities(emailDummyIntent, 0);
}
public static Intent getEmptyEmailIntent() {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse(INTENT_DATA_SCHEME_EMAIL));
return emailIntent;
}
private static void grantReadPermissionForAttachmentUri(Context context,
Intent emailIntent,
Uri attachmentUri) {
if (emailIntent == null || attachmentUri == null) {
return;
}
context.grantUriPermission(emailIntent.getComponent().getPackageName(),
attachmentUri,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
private void sendEmailUsingSelectedEmailClient(Context context,
ResolveInfo emailClient,
EmailSenderListener listener) {
try {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, null != subject ? subject : "");
emailIntent.putExtra(Intent.EXTRA_TEXT, null != body ? body : "");
emailIntent.setComponent(new ComponentName(emailClient.activityInfo.packageName, emailClient.activityInfo.name));
addAttachment(context, attachment, emailIntent);
listener.onEmailIntentReady(emailIntent);
} catch (Exception ex) {
Timber.e("Error sending email", ex);
}
}
private static void addAttachment(Context context, File attachment, Intent emailIntent) {
if (attachment != null) {
Uri contentUri = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORIZER, attachment);
grantReadPermissionForAttachmentUri(context, emailIntent, contentUri);
emailIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
}
}
public interface EmailSenderListener {
void onEmailIntentReady(Intent emailIntent);
}
}
I've added an email intent to an Android app with code to add a local file as an attchment.
But when I click "Email Data" button to open the intent I get a an app crash
and log cat shows the following, http://hastebin.com/idejavunam.avrasm , an error of null pointer exception is output at this line:
case R.id.emailBtn:
so I thought its a problem with the file uri but can't see why as the file exists in the device's file system.
Does anyone know how I can debug this issue?
Possibly I'm passing the file's path to email intent incorrectly?
This is the process I'm following to implement the solution.
code from the method that creates csv file:
String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "AnalysisData.csv";
//this filePath is used in email code and converted to Uri.
filePath = baseDir + File.separator + fileName;
File f = new File(filePath);
And this is the code where the email intent is called, with the file path converted to a Uri for attachment prposes:
case R.id.emailBtn: {
Toast.makeText(this, "email clicked", Toast.LENGTH_SHORT).show();
Uri.fromFile(new File(filePath));
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","abc#gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "EXTRA_SUBJECT");
emailIntent.putExtra(Intent.EXTRA_STREAM, filePath);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
break;
I have modified some part check, if it works now.
case R.id.emailBtn: {
Toast.makeText(this, "email clicked", Toast.LENGTH_SHORT).show();
Uri uri = Uri.fromFile(new File(filePath));
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","abc#gmail.com", null));
emailIntent.setType("*/*");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "EXTRA_SUBJECT");
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
break;
UPDATE
Also after looking at the logcat I found that your filepath is null . kindly correct that
EDIT
I have modified your onClick Method simply replace tell me if it works for you
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "AnalysisData.csv";
filePath = baseDir + File.separator + fileName;
File f = new File(filePath);
switch (v.getId()) {
case R.id.exportBtn: {
Toast.makeText(this, "select clicked", Toast.LENGTH_SHORT).show();
//write sample data to csv file using open csv lib.
date = new Date();
CSVWriter writer = null;
// File exist
if(f.exists() && !f.isDirectory()){
FileWriter mFileWriter = null;
try {
mFileWriter = new FileWriter(filePath , true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
writer = new CSVWriter(mFileWriter);
}
else {
try {
writer = new CSVWriter(new FileWriter(filePath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String data [] = new String[] {"Record Number","Ship Name","Scientist Name","Scientist Email","Sample Volume","Sample Colour","Sample Material","Latitude","Longitude","Date","\r\n"};
writer.writeNext(data);
/*
//retrieve record cntr from prefs
SharedPreferences settings = getSharedPreferences("RECORD_PREF", 0);
recordCntr = settings.getInt("RECORD_COUNT", 0); //0 is the default value
*/
//increment record count
recordCntr++;
/*
//save record cntr from prefs
settings = getSharedPreferences("RECORD_PREF", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("RECORD_COUNT",recordCntr);
editor.commit();
*/
data = new String[]{Integer.toString(recordCntr),shipName,analystName,analystEmail,sampleVolume,
sampleColour,sampleMaterial,latitudeValue.toString(),longitudeValue.toString(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date),"\r\n"};
writer.writeNext(data);
try {
writer.close();
Toast.makeText(this, "Data exported succesfully!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "Error exporting data!", Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.emailBtn: {
Toast.makeText(this, "email clicked", Toast.LENGTH_SHORT).show();
if (f.exists() && !f.isDirectory()) {
Uri uri = Uri.fromFile(f);
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","abc#gmail.com", null));
emailIntent.setType("*/*");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "EXTRA_SUBJECT");
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
break;
}
}
}
I have an android application which sends a .csv file as attachement, i have given permsissions in the manifest and reffered to lot of codes but everytime when i send an attachement, the mail comes without the attachement. I have referred to many stackoverflow solutions but they do not have effect at all.
here is the code.
sendmail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendEmail();
}
protected void sendEmail() {
Log.i("Send email", "");
String TO = email.getText().toString();
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{TO});
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("excerDB.csv"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your ward's academic details are here");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Please find the details attached....");
startActivity(emailIntent);
try {
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(DisplayContact.this,
"There is no email client installed.", Toast.LENGTH_SHORT).show();
}
}
});
P.S :- i tried it running on gennymotion emulator and on a real device.
Attachement not getting attached in android while sending mail
Becuase you are not passing right path of csv file to Uri.parse.
To create valid URI you should provide complete path of file :
Uri uriFile=Uri.parse(<File_Location_On_Int./Ext. Sd_Card>+"/excerDB.csv");
Now use uriFile as EXTRA_STREAM key value.
You EXTRA_STREAM variable is wrong :
try below :
Open a gallery to choose file from button click :
public void openGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
On Activity Result save the URI ;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
/**
* Get Path, chnage type accordingly
*/
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
attachmentFile = cursor.getString(columnIndex);
Log.e("Attachment Path:", attachmentFile);
URI = Uri.parse("file://" + attachmentFile);
cursor.close();
}
}
Hello stackoverflow community,
I searched alot about attaching a photo to an email. I found code which worked, but the picture had a bad resolution. Now I want to send the picture uncompressed. Therefore I looked through many questions and found this piece of code,
but when taking the photo, I can't accept it and move on.
Here you can look into my code:
this.eco.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File path = new File("/Pictures/");
path.mkdirs();
String fileName = "verunreinigung.jpg";
File file = new File(path, fileName);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Uri.fromFile(file));
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
// variables
int latitude = GMapsSubActivity.getLatitude();
int longitude = GMapsSubActivity.getLongitude();
double dLat = latitude / 1000000.0;
double dLng = longitude / 1000000.0;
Log.v("lat", Integer.toString(latitude));
Log.v("lng", Integer.toString(longitude));
Log.v("lat", Double.toString(dLat));
Log.v("lng", Double.toString(dLng));
String[] address = new String[]{cursor.getString(cursor.getColumnIndex("email"))};
String subject = "Verunreinigung am Gewässer: " + cursor.getString(cursor.getColumnIndex("gewName"))
+ " / " + cursor.getString(cursor.getColumnIndex("reviergrenzen"));
String text = "Hallo " + cursor.getString(cursor.getColumnIndex("name"))
+ "!\n\nIch habe an/in Ihrem Gewässer eine"
+ " Verunreinigung entdeckt.\n"
+ "Sie befindet sich hier:\n"
+ "http://maps.google.com/?q=" + dLat + "," + dLng + "\n"
+ "Das Foto finden Sie im Anhang.\n\nLiebe Grüße!";
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "photo");
values.put(Images.Media.BUCKET_ID, "photo_ID");
values.put(Images.Media.DESCRIPTION, "");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri photoUri = getContentResolver().insert(
Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(photoUri);
photo.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// define the intent
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, address);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, text);
emailIntent.putExtra(Intent.EXTRA_STREAM, photoUri);
emailIntent.setType("plain/text");
// start the intent
try {
startActivity(Intent.createChooser(emailIntent,
"Versende Email via:"));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(),
"Kein Email-Programm installiert.", Toast.LENGTH_SHORT)
.show();
}
}
}
Use the below code to send a mail
String filelocation="/mnt/sdcard/capture.png";
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
String to[] = "user#gmail.com";
sharingIntent.putExtra(Intent.EXTRA_EMAIL, to);
sharingIntent.putExtra(Intent.EXTRA_STREAM,filelocation);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT,"subject");
startActivity(Intent.createChooser(sharingIntent, "Send email"));
i have a problem to send mail with attachment. I'm using Javamail libraries (mail.jar, activitation.jar and additional.jar ). I can send mail accurately. But i can not send mail with an attachment is image to mail. I choose an image from gallery, and it is addded as my filename
File f = new File("file://" + uri.getPath());
I think i have a problem when datasource took the my file's path. Whatever you can see much more thing in my code:(i've solved this problem and it is the last situation of my code)
first of all i add to view of my attachment :
Button Add = (Button) findViewById(R.id.btnAdd);
Add.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
onAddAttachment2("image/*");
}
});
here is my onAddAttachment2 and onActivityResult code
private void onAddAttachment2(final String mime_type) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(mime_type);
startActivityForResult(Intent.createChooser(i, null),
ACTIVITY_REQUEST_PICK_ATTACHMENT);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
mAttachments = (LinearLayout) findViewById(R.id.attachments);
switch (requestCode) {
case ACTIVITY_REQUEST_PICK_ATTACHMENT:
Uri _uri = imageReturnedIntent.getData();
addAttachment(_uri);
Cursor cursor = getContentResolver()
.query(_uri,
new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
null, null, null);
cursor.moveToFirst();
String imageFilePath = cursor.getString(0);
uris.add(imageFilePath);
Log.v("imageFilePath", imageFilePath);
break;
}
}
As u see there is i have an AddAttachment method. Here is the code:
private void addAttachment(Uri uri) {
addAttachment(uri, null);
}
private void addAttachment(Uri uri, String contentType) {
long size = -1;
String name = null;
ContentResolver contentResolver = getContentResolver();
Cursor metadataCursor = contentResolver.query(uri, new String[] {
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }, null,
null, null);
if (metadataCursor != null) {
try {
if (metadataCursor.moveToFirst()) {
name = metadataCursor.getString(0);
size = metadataCursor.getInt(1);
}
} finally {
metadataCursor.close();
}
}
if (name == null) {
name = uri.getLastPathSegment();
}
String usableContentType = contentType;
if ((usableContentType == null)
|| (usableContentType.indexOf('*') != -1)) {
usableContentType = contentResolver.getType(uri);
}
if (usableContentType == null) {
usableContentType = getMimeTypeByExtension(name);
}
if (size <= 0) {
String uriString = uri.toString();
if (uriString.startsWith("file://")) {
Log.v(LOG_TAG, uriString.substring("file://".length()));
File f = new File(uriString.substring("file://".length()));
size = f.length();
} else {
Log.v(LOG_TAG, "Not a file: " + uriString);
}
} else {
Log.v(LOG_TAG, "old attachment.size: " + size);
}
Log.v(LOG_TAG, "new attachment.size: " + size);
Attachment attachment = new Attachment();
attachment.uri = uri;
attachment.contentType = usableContentType;
attachment.name = name;
attachment.size = size;
View view = getLayoutInflater().inflate(
R.layout.message_compose_attachment, mAttachments, false);
TextView nameView = (TextView) view.findViewById(R.id.attachment_name);
ImageButton delete = (ImageButton) view
.findViewById(R.id.attachment_delete);
nameView.setText(attachment.name);
delete.setTag(view);
view.setTag(attachment);
mAttachments.addView(view);
delete.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
uris.remove(view.getTag());
mAttachments.removeView((View) view.getTag());
}
});
}
and Attachment class that has properties
static class Attachment implements Serializable {
private static final long serialVersionUID = 3642382876618963734L;
public String name;
public String contentType;
public long size;
public Uri uri;
}
finally in my Mail.java class i have AddAttachment method:
public void addAttachment(String file) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file);
_multipart.addBodyPart(messageBodyPart);
}
When i clicked to send button, it have been sending to adress is written.
But my attachment can not be shown. I have no error when i sent mail. I hope you had a solution for these problem...
Edit: OK finally i've solved the problem!..
first i've defined ArrayList<String> uris = new ArrayList<String>();
Then i've used it in my onActivityResult method like that uris.add(imageFilePath);
lastly, before m.send code block i've add the images:
for (int i = 0; i<uris.size(); i++)
{
m.addAttachment(uris.get(i).toString());
}
in my Mail.java class, the changes shown like that :
public void addAttachment(String file) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file);
_multipart.addBodyPart(messageBodyPart);
}
There definitely the problem of MIME Type. If you want to image attached with email you can send this with simply using
private void sendEmail(String[] to,String[] cc,String subject, String message)
{
ArrayList<Uri> uris = new ArrayList<Uri>();
Uri u = Uri.fromFile(new File(front_image));
Uri u1 = Uri.fromFile(new File(side_image));
uris.add(u);
uris.add(u1);
Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("image/jpg");
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_CC, cc);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
/*emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_right_latest_path));
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_right_prev_path));
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_front_latest_path));
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_front_prev_path));*/
startActivity(Intent.createChooser(emailIntent, "Email"));
}
I hope the string you're passing to the addAttachment method is a file name, not a URL (i.e., doesn't start with "file:").
To debug your problem, add code to the addAttachment method that uses a FileInputStream and see if you can read the data in the file. If you can't, JavaMail won't be able to either.
Also, turn on Session debugging and examine the protocol trace to see what JavaMail is actually sending. That might provide more clues. Or, in your code that actually sends the message, add msg.writeTo(new FileOutputStream("msg.txt")) and see what's written to the file.