Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Send email with attachment in Android

4.67/5 (9 votes)
13 Oct 2011CPOL 75.7K  
How to send an email with attachment in Android.

Imagine you are implementing a program for a sales rep that has to print an invoice (reciept) when he is with the client. There is no wifi printer or connection with a local network.


A solution that comes to mind is to send the invoice to the client by email and then he can print it locally.
We will create a function to create the HTML file (invoice file) and save the HTML to an SD card. Note that you have to change the code regarding the invoice details, I just put a sample:


Java
private void createFile() {
try {
String data = "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/><html><body style='tab-interval: .5in'><div class="Section1"><div>";
data += "<p class="MsoNormal" dir="LTR" style="text-align: left; unicode-bidi: embed"><span lang="AR-EG">";
FileOutputStream fos = new FileOutputStream(strFile);

Writer out = new OutputStreamWriter(fos, "UTF-8");

data += "Email data" + "<br />";
data += "bla bla bla" + "<br />";
data += "Footer" + "<br />";

data += "</span></p></div></body></html>";
out.write(data);
out.flush();
out.close();

} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}

Now we need code to fire the sending event.



You can add a test box (Edit view) to the activity to let the user write the address and subject, we will use a static variable with fixed variables.


Java
public void clickbutton(View v) {
try {
strFile = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/temp";

File file = new File(strFile);
if (!file.exists())
file.mkdirs();
strFile = strFile + "/report.html";
createFile();
//
Log.i(getClass().getSimpleName(), "send  task - start");
//
final Intent emailIntent = new Intent(
android.content.Intent.ACTION_SEND);
//
address = "hamdy.ghanem@gmail.com";
subject = "Recite";
emailtext = "Please check the attached recite";
//
emailIntent.setType("plain/text");

emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[] { address });

emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);

emailIntent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + strFile));

emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext);

this.startActivity(Intent
.createChooser(emailIntent, "Send mail..."));

} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)