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 :)
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 developing an android application and i need to share the image on button click.But i am getting Image URl only. So, how can i share the image???
And i am getting empty attachment if i give image URL to the intent.
my code is:
sharebut =(Button)findViewById(R.id.sharebut);
sharebut.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
String screenshotUri = flag;
sharingIntent.setType("image/*");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}
});
Add the path where your image is located in sd card in Uri.parse("file:///"+ yourImagePath)
Use :
String path= "/Downloads/image1.jpg"; //Add your path here
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///"+ path));
Please try this solution for share image via email from URL.
String path = "";
URL url;
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setClassName("com.google.android.gm",
"com.google.android.gm.ComposeActivityGmail");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, description);
try {
url = new URL(thumnbnailURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap immutableBpm = BitmapFactory.decodeStream(input);
Bitmap mutableBitmap = immutableBpm.copy(
Bitmap.Config.ARGB_8888, true);
View view = new View(VideoDetailsActivity.this);
view.draw(new Canvas(mutableBitmap));
path = Images.Media.insertImage(getContentResolver(),
mutableBitmap, "Nur", null);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Uri uri = Uri.parse(path);
intent.setType("application/image");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(intent);
I found the solution.. :)
Just created a file and share the content in imageview.
sharebut =(Button)findViewById(R.id.sharebut);
sharebut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
imgflag.buildDrawingCache();
Bitmap bmap = imgflag.getDrawingCache();
OutputStream out = null;
String path =Environment.getExternalStorageDirectory().toString();
File file = new File(path, "test.png");
try {
file.createNewFile();
out = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share Your Image"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
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.
I want to save a contact data which is in VCard format in user's contacts via sending intent. Is there any way to do it?
NOTE: I don't want to save VCard data in a .vcf file and then give it's uri to intent like the code below.
String scanned = "..." // contact in VCard format
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
File vcfFile = new File(getCacheDir(), "tmp.vcf");
try {
FileOutputStream fos = new FileOutputStream(vcfFile);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(scanned);
osw.close();
fos.close();
i.setDataAndType(Uri.fromFile(vcfFile), "text/vcard");
startActivity(i);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If the contact is indeed in the contacts database, you could look at the android contacts app's code, to see how to share a vcard out of it (found from here, inside a file called "QuickContactActivity.java" ) :
private void shareContact() {
final String lookupKey = mContactData.getLookupKey();
final Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(Contacts.CONTENT_VCARD_TYPE);
intent.putExtra(Intent.EXTRA_STREAM, shareUri);
// Launch chooser to share contact via
final CharSequence chooseTitle = getText(R.string.share_via);
final Intent chooseIntent = Intent.createChooser(intent, chooseTitle);
try {
mHasIntentLaunched = true;
ImplicitIntentsUtil.startActivityOutsideApp(this, chooseIntent);
} catch (final ActivityNotFoundException ex) {
Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show();
}
}
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