Click here to Skip to main content
15,881,757 members
Articles / Mobile Apps / Android
Tip/Trick

Send email with attachment in Android

Rate me:
Please Sign up or sign in to vote.
4.67/5 (9 votes)
13 Oct 2011CPOL 74.8K   16   4
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)


Written By
Software Developer (Senior)
Egypt Egypt
Hamdy Ghanem
Senior Software Engineer / System Architect
Experience: +11 years
http://www.linkedin.com/in/hamdyghanem
hamdy.ghanem@gmail.com
Graduated from Munifia University, faculty of science, Math and computer science department May 1999

Experience Brief
11+ years of experience in software development field.
In these years I used most of common software developing tools of Microsoft, And with many nationalities and cultures.
I worked in large scale projects of client side, desktop, web application and mobile phones that involved integration with other system using different technologies I've been working using .NET technologies for 8 years.
Currently, I work as a senior software engineer for CogWin as well as a testing/QA consultant. We develop large scale applications for a high profile customer.
Beside developing and managing, I worked in the last year as a professional tester from developer point of view and applying software evaluation metrics on source code and reverse engineering.
I worked as a team leader more than four years
My experience involved using agile methodology using team foundation server
from 1year I am very interested in Android development
I have a published some applications in the Android Market

Strong skills troubleshooting and debugging production systems are essential
My key skills
High performance, hard worker and new technologies enthusiast
Specialties
C#,VB.net, C++, Java ,php, Python , OOP SQL Server (2000, 2005, 2008),Oracle, Mysql , Java , SSRS ,Source safe, Ontology, Android, ASP.NET ,Ajax, • WPF,WCF, Entity Framework, LINQ, CFG , state machine , Ontology, Decision Tree , Cloud Systems, CRM ,JavaScript, XML, UML, Crystal report , LINQ, Silverlight

Comments and Discussions

 
QuestionI have one error - Attachment not send Pin
srihari190415-Sep-14 4:37
srihari190415-Sep-14 4:37 
QuestionNice Post!! Great Pin
boss prabu7-Jul-13 7:42
boss prabu7-Jul-13 7:42 
Thanks for the code snippet, was really useful.. Even this http://www.compiletimeerror.com/2013/07/send-email-in-android-example.html[^] might be helpful.. Have a look....
GeneralReason for my vote of 3 no form design Pin
virgiyana9-Jan-12 15:00
virgiyana9-Jan-12 15:00 
GeneralReason for my vote of 5 Just as I was researching the subjec... Pin
Emad Sammour14-Oct-11 10:26
Emad Sammour14-Oct-11 10:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.