Attachment is not coming in mail programmatically - android

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);
}
}

Related

Action_Send_Multiple intent, but not sure how to build the array

So in my current form of my app, I am able to send an email with a single image using the following:
private void dispatchSubmitBonusIntent() {
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendEmailIntent.setType("text/plain");
sendEmailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{submissionEmailAddress});
sendEmailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "2019_" + riderNumToH + "_" + bonusCategory.getText() +"_" + bonusState.getText() + "_" + bonusCity.getText() + "_" + bonusCode.getText());
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, "Sent from aTOH App");
if (mainPhotoPath != null) {
sendEmailIntent.putExtra(android.content.Intent.EXTRA_STREAM, FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", mainPhotoUri));
Log.v("MainImageFound", mainPhotoPath + "|" + mainPhotoUri);
if (secondaryPhotoPath != null) {
sendEmailIntent.putExtra(android.content.Intent.EXTRA_STREAM, FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", secondaryPhotoUri));
Log.v("SecondaryImageFound", secondaryPhotoPath + "|" + secondaryPhotoUri);
} else {
Log.e("NoImageFound", "Image Not Found");
}
}
this.startActivity(Intent.createChooser(sendEmailIntent, "Sending email..."));
}
I am needing it to send up to two attachments, so I'm converting it over to an ACTION_SEND_MULTIPLE. I have the following code, but I'm not sure what to put inside the for loop for it to work.
public void sendEmail(Context context, String emailTo, String emailCC,
String subject, String emailText, List<String> filePaths)
{
//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,
new String[]{submissionEmailAddress});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "2019_" + riderNumToH + "_" + bonusCategory.getText() +"_" + bonusState.getText() + "_" + bonusCity.getText() + "_" + bonusCode.getText());
emailIntent.putExtra(Intent.EXTRA_TEXT, "Sent from aTOH App");
//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(Intent.createChooser(emailIntent, "Sending email ..."));
}
What do I put in the for section so the it will grab the one or two images that need to be attached?
EDIT 1: I made some changes based on the answer I was given, but it still isn't working. I get an error that says android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Tour%20of%20Honor/2019_541_AK6_1.jpg exposed beyond app through ClipData.Item.getUri() (That file path is correct though).
public void dispatchSubmitBonusIntent() {
Log.e(TAG, "entering dispatchSubmitBonusIntent");
//need to "send multiple" to use more than one attachment
final Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
// Set up the email parameters
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[]{submissionEmailAddress});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "2019_" + riderNumToH + "_" + bonusCategory.getText() +"_" + bonusState.getText() + "_" + bonusCity.getText() + "_" + bonusCode.getText());
emailIntent.putExtra(Intent.EXTRA_TEXT, "Sent via TOH App for Android");
// Get the attachments
Uri mainPhotoURI = FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", mainPhotoUri);
Uri optPhotoURI = FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", secondaryPhotoUri);
//has to be an ArrayList
ArrayList<Uri> uris = new ArrayList<Uri>();
String[] filePaths = new String[] {mainPhotoURI.toString(), optPhotoURI.toString()};
for (String file : filePaths)
{
File fileIn = new File(file);
Uri u = Uri.fromFile(fileIn);
uris.add(u);
}
// Add the attachments to the email and trigger the email intent
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
this.startActivity(Intent.createChooser(emailIntent, "Sending email ..."));
}
Create one method for sending multiple attachments using an array
public boolean sendEmailIntentWithMultipleAttachments(Context context,
String[] emailTo, String[] emailCC, String[] emailBCC,
String subject, String emailBody, List filePaths) throws ActivityNotFoundException {
final Intent emailIntent =
new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailTo);
emailIntent.putExtra(android.content.Intent.EXTRA_CC, emailCC);
emailIntent.putExtra(android.content.Intent.EXTRA_BCC, emailBCC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
ArrayList<String> extra_text = new ArrayList<String>();
extra_text.add("Hello This is multiple Email Text");
ei.putStringArrayListExtra(Intent.EXTRA_TEXT, extra_text);
if (filePaths != null) {
// has to be an ArrayList
ArrayList uris = new ArrayList();
// convert from paths to Android friendly Parcelable Uri's
for (String file : filePaths) {
File fileIn = new File(file);
if (fileIn.exists()) {
Uri u = Uri.fromFile(fileIn);
uris.add(u);
}
}
emailIntent.putParcelableArrayListExtra
(Intent.EXTRA_STREAM, uris);
}
context.startActivity(Intent.createChooser(emailIntent, "Sent mail"));
return true;
}
Create an imageArray like this and set to intent putParcelableArrayListExtra
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);
Its working fine in my app

Android email intent not attaching files as attachment

For my company i am trying to send email from my android app using email intent.
I'm using emulator to test my app. But the problem is when i'm trying to Add and Attachment (eg. pdf, image) it won't attaching yet.
here is my code:
private String SendEmail(String oid, final String img, final String party_code, final String order_by, final Bitmap attachimg, final String note) {
try {
String filename="DOAttachment.jpeg";
String subject ="Order "+oid+" has been sent successfully";
String body="\nDear Sir, \n"+"Please find the attached file herewith.\nThe D.O for the customer(party) "+party_code+" has been successfully done with the order number: "+oid+"\n\n\n"+"With regards \n \n Employee code/ID: "+order_by+"\n\nN.B:"+note;
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "DirName/"+filename;
File file = new File(root, pathToMyAttachedFile);
file.setReadable(true,false);
Log.e("File path"," "+file);
//using outlook
Intent intent = new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|FLAG_ACTIVITY_SINGLE_TOP);
intent.setType("image/*");
Uri data = Uri.parse("mailto:?subject=" + subject + "&body=" + body+ "&stream="+Uri.parse("file:///"+Environment.getExternalStorageDirectory().getAbsolutePath())+"/DirName/"+filename);
intent.setData(data);
intent .putExtra(Intent.EXTRA_EMAIL, toemail);
if (!file.exists() || !file.canRead()||!file.canWrite()) {
Log.e(" FILE ERROR ","File Not found");
Toast.makeText(getApplicationContext(),"File Not found",Toast.LENGTH_LONG).show();
}
else {
file.setReadable(true);
Log.e(" FILE OK ","File was found");
Uri uri = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
return "TRUE";
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
return "MAIL NOT SENT";
}
}
The result is email with empty attachment find screenshot : https://1drv.ms/i/s!AruisQQIx8MTgatuhJFmSaoArg_6Xw
Check whether you had provided READ_EXTERNAL_STORAGE permission for your application both in manifest and run-time.
Then Call the below method send mail assuming the full file path is saved in filePath.
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "DirName/"+filename;
File filePath = new File(root, pathToMyAttachedFile)
sendEmailAlert(filePath,subject,text);
CALLED METHOD
private void sendEmailAlert(File fileName,String subject,String text) {
final File file=fileName;
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream"); /* or use intent.setType("message/rfc822); */
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
if (!file.exists() || !file.canRead()) {
Toast.makeText(getContext(), "Attachment Error", Toast.LENGTH_SHORT).show();
return;
}
Uri uri = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Send email..."));
}

how to attach file in android using gmail

((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.

attach image from camera to email - android

I have a button which takes a photo, stores the thumbnail in an Imageview, and when the user clicks another button, it needs to attach that image to an email.
Ive followed the "Taking Photos Simply" directions from the Android site, but there is no attachment included. Can somebody see where i am going wrong, and what I need to do to fix it?
My on Activity Result code:
public void onActivityResult(int requestcode, int resultcode, Intent data) {
if (requestcode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultcode == RESULT_OK) {
Bundle bundle = new Bundle();
bundle = data.getExtras();
Bitmap BMB;
BMB = (Bitmap) bundle.get("data");
Hoon_Image.setImageBitmap(BMB);
try {
createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
mDrawable = Hoon_Image.getDrawable();
mBitmap = ((BitmapDrawable) mDrawable).getBitmap();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
my email intent:
if (Witness_response == "Yes"){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"roadsafety.app#shellharbour.nsw.gov.au"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Dob in a Hoon Report (Y)");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Hoon report has been recieved " + emailBody);
emailIntent.putExtra(Intent.EXTRA_STREAM, mCurrentPhotoPath );
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Choose email client..."));
} else if (Witness_response == "No"){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"roadsafety.app#shellharbour.nsw.gov.au"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Dob in a Hoon Report (N)");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Hoon report has been recieved " + emailBody);
emailIntent.putExtra(Intent.EXTRA_STREAM, mCurrentPhotoPath);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Choose email client..."));
}
try this code
public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private File f;
public File getAlbumDir()
{
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
"BAC/"
);
// Create directories if needed
if (!storageDir.exists()) {
storageDir.mkdirs();
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName =getAlbumDir().toString() +"/image.jpg";
File image = new File(imageFileName);
return image;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
f = createImageFile();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = BitmapFactory.decodeFile(f.getAbsolutePath());
imageView.setImageBitmap(photo);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"email id"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
Uri uri = Uri.fromFile(f);
i.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
}
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("image/*");
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);
startActivity(Intent.createChooser(emailIntent, "Send Mail"));;
and here,
uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), FILENAME));

can not send mail with attachment in Android

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.

Categories

Resources