Sending email using an Android app, which we custom build using with GMail SMTP using JavaMail API will be fun. With respect to using GMail’s SMTP server to send email is simple and easy to do. Code for the component of sending email in Java platform and Android app are same. Jars used from JavaMail API will be different for Java platform and Android, but the code we write will be same.
I already wrote a tutorial for sending email using Java and GMail SMTP with JavaMail API. Refer that for understanding about the core service of sending email. It has got couple of steps only and easy to understand.
Here in this Android tutorial, we will reuse that same code which used to send email using GMail from Java. Remember we cannot use the same Jar files that we used from JavaMail API, but we need to use the ported version of JavaMail for Android. As far as GMail provides its SMTP server for our use, we can enjoy it for free like this, thanks to Google. We should have an email id created from GMail.
There three important source files that needs to be discussed in this example Android app for sending Email using GMail,
This Java class is not specific to Android and can also be used in general Java SE platform by using the general JavaMail API jars.
package com.javapapers.android.androidjavamail; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import android.util.Log; public class GMail { final String emailPort = "587";// gmail's smtp port final String smtpAuth = "true"; final String starttls = "true"; final String emailHost = "smtp.gmail.com"; String fromEmail; String fromPassword; ListtoEmailList; String emailSubject; String emailBody; Properties emailProperties; Session mailSession; MimeMessage emailMessage; public GMail() { } public GMail(String fromEmail, String fromPassword, List toEmailList, String emailSubject, String emailBody) { this.fromEmail = fromEmail; this.fromPassword = fromPassword; this.toEmailList = toEmailList; this.emailSubject = emailSubject; this.emailBody = emailBody; emailProperties = System.getProperties(); emailProperties.put("mail.smtp.port", emailPort); emailProperties.put("mail.smtp.auth", smtpAuth); emailProperties.put("mail.smtp.starttls.enable", starttls); Log.i("GMail", "Mail server properties set."); } public MimeMessage createEmailMessage() throws AddressException, MessagingException, UnsupportedEncodingException { mailSession = Session.getDefaultInstance(emailProperties, null); emailMessage = new MimeMessage(mailSession); emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail)); for (String toEmail : toEmailList) { Log.i("GMail","toEmail: "+toEmail); emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); } emailMessage.setSubject(emailSubject); emailMessage.setContent(emailBody, "text/html");// for a html email // emailMessage.setText(emailBody);// for a text email Log.i("GMail", "Email Message created."); return emailMessage; } public void sendEmail() throws AddressException, MessagingException { Transport transport = mailSession.getTransport("smtp"); transport.connect(emailHost, fromEmail, fromPassword); Log.i("GMail","allrecipients: "+emailMessage.getAllRecipients()); transport.sendMessage(emailMessage, emailMessage.getAllRecipients()); transport.close(); Log.i("GMail", "Email sent successfully."); } }
In our example, this is the default Android Activity for the Android app. This is the email compose screen, when we start this example app we will just directly land in the email compose page. It will have the basic email fields like, from, to, subject, body. We can give the from email address and its respective password as input argument. This example app uses above GMail.java class to send email which comes with default settings that is configured for sending email with GMail SMTP. So if you want to use any other SMTP server, then we have to update the smtp settings there.
package com.javapapers.android.androidjavamail; import java.util.Arrays; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; public class SendMailActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_mail); final Button send = (Button) this.findViewById(R.id.button1); send.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.i("SendMailActivity", "Send Button Clicked."); String fromEmail = ((TextView) findViewById(R.id.editText1)) .getText().toString(); String fromPassword = ((TextView) findViewById(R.id.editText2)) .getText().toString(); String toEmails = ((TextView) findViewById(R.id.editText3)) .getText().toString(); ListtoEmailList = Arrays.asList(toEmails .split("\\s*,\\s*")); Log.i("SendMailActivity", "To List: " + toEmailList); String emailSubject = ((TextView) findViewById(R.id.editText4)) .getText().toString(); String emailBody = ((TextView) findViewById(R.id.editText5)) .getText().toString(); new SendMailTask(SendMailActivity.this).execute(fromEmail, fromPassword, toEmailList, emailSubject, emailBody); } }); } }
I have used AsyncTask, as sending email is best done in a separate thread. SendMailActivity will receive the user email arguments and pass it on to the SendMailTask to send email. SendMailTask interacts with GMail.java by passing parameters to and publishing mail sending status using ProgressDialog.
package com.javapapers.android.androidjavamail; import java.util.List; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; public class SendMailTask extends AsyncTask { private ProgressDialog statusDialog; private Activity sendMailActivity; public SendMailTask(Activity activity) { sendMailActivity = activity; } protected void onPreExecute() { statusDialog = new ProgressDialog(sendMailActivity); statusDialog.setMessage("Getting ready..."); statusDialog.setIndeterminate(false); statusDialog.setCancelable(false); statusDialog.show(); } @Override protected Object doInBackground(Object... args) { try { Log.i("SendMailTask", "About to instantiate GMail..."); publishProgress("Processing input...."); GMail androidEmail = new GMail(args[0].toString(), args[1].toString(), (List) args[2], args[3].toString(), args[4].toString()); publishProgress("Preparing mail message...."); androidEmail.createEmailMessage(); publishProgress("Sending email...."); androidEmail.sendEmail(); publishProgress("Email Sent."); Log.i("SendMailTask", "Mail Sent."); } catch (Exception e) { publishProgress(e.getMessage()); Log.e("SendMailTask", e.getMessage(), e); } return null; } @Override public void onProgressUpdate(Object... values) { statusDialog.setMessage(values[0].toString()); } @Override public void onPostExecute(Object result) { statusDialog.dismiss(); } }
Android Manifest has got the usual configuration and we need to add an extra line. This is for giving permission for our Android app to access internet to send email using GMail.
<uses-permission android:name="android.permission.INTERNET"/>
I have not provided the dependent JavaMail jars with the project source code download below. You need to download jars mail.jar, activation.jar and additional.jar from JavaMail-android download page.
Comments are closed for "Android Email App with GMail SMTP using JavaMail".
Fantastic. thanks a lot.
Are you publishing android apps. I hope if you do, they will be great.
Thanks for this tutorial but i am confused about the Password thing. Is it actual gmail account password?
thanq you joe sir……………..
fine sir nice artical can u pls tell me
if a runtime exception is thrown in the finalize method The exception is simply ignored and the object is garbage collected.
why so this behaviour?? (waiting for replay)
It was so helpFul
Fabulous
Sir,
Thanx for the code.But I am getting Force Close whan I click on Sendmail.Please give me suggestion to solve the problem.
Thanks Joe, this works perfectly for my app.
Hi Joe, this is a fantastic tutorial. But I am having an issue. similar to this one.
I have an app which shows map and button on it. I want to notify the user’s current location to another mobile, when I click on that button. (just like facebook chat. when One friend sends message to second friend, second friend gets notified)
How do I do that? Please help!
Very informative; Thanks for sharing.
How we can use UTF8 for sending other language?
Thanks for your answer.
[…] far we have seen how we can send email in Java using JavaMail API and then an email app in Android using JavaMail API and GMail SMTP. Now to complete this email series (at least for now), we shall do email with Spring and […]
Having warning in SendMailActivity.java
String emailBody = ((TextView) findViewById(R.id.editText5))
.getText().toString();
new SendMailTask(SendMailActivity.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
}
});
}
}
Last two lines showing error. and not working .
thanks a lot sir
Having warning in SendMailActivity.java
String emailBody = ((TextView) findViewById(R.id.editText5))
.getText().toString();
new SendMailTask(SendMailActivity.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
}
});
}
}
One more problem..
I am getting Force Close whan I click on Sendmail.Please give me suggestion to solve the problem.
plzzzzzzzzzzzzzzz urgent
Hi Joe:
Thanks for this tutorial is very useful. I have a question, if you could answer I would really aprecite it.
I follow this tutorial and create an application, but the problem is that it works normally in my Android 2.3 cell. But in my Lenovo A3300 Android 4.2.2 tablet don’t send the message LogCat says that cannot be connected to smtp 587 port.
Please a I need any respond
Best Regards
Jose,
Need more information to resolve this. Check for information in LogCat, we should find out why its not able to connect to smtp port.
plz help me
01-11 13:48:59.818: E/MailApp(29958): Could not send email
01-11 13:48:59.818: E/MailApp(29958): android.os.NetworkOnMainThreadException
01-11 13:48:59.818: E/MailApp(29958): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
01-11 13:48:59.818: E/MailApp(29958): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
01-11 13:48:59.818: E/MailApp(29958): at java.net.InetAddress.getLocalHost(InetAddress.java:371)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.InternetAddress.getLocalAddress(InternetAddress.java:517)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.UniqueValue.getUniqueMessageIDValue(UniqueValue.java:99)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.updateMessageID(MimeMessage.java:2054)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2076)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2042)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.Transport.send(Transport.java:117)
01-11 13:48:59.818: E/MailApp(29958): at com.fahadalawam.kwtresturant.Mail.send(Mail.java:125)
01-11 13:48:59.818: E/MailApp(29958): at com.fahadalawam.kwtresturant.Add$1.onClick(Add.java:58)
01-11 13:48:59.818: E/MailApp(29958): at android.view.View.performClick(View.java:3480)
01-11 13:48:59.818: E/MailApp(29958): at android.view.View$PerformClick.run(View.java:13983)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Handler.handleCallback(Handler.java:605)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Handler.dispatchMessage(Handler.java:92)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Looper.loop(Looper.java:137)
01-11 13:48:59.818: E/MailApp(29958): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-11 13:48:59.818: E/MailApp(29958): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 13:48:59.818: E/MailApp(29958): at java.lang.reflect.Method.invoke(Method.java:511)
01-11 13:48:59.818: E/MailApp(29958): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-11 13:48:59.818: E/MailApp(29958): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-11 13:48:59.818: E/MailApp(29958): at dalvik.system.NativeStart.main(Native Method)
it gives error “Unfortunately app has stopped” cant solve help!!! asap
Hi,
thanks for a very nice tutorial. I have a question though.
Why do we need to use the javamail-android port? Are there some problems with the standard javamail implementation on Android?
My only concern is that the last version is from September 2009.
Thanks for your help
Example is not working please send me working zip file
when i run the error is coming
like11-19 12:14:39.835: E/AndroidRuntime(18910): at com.javapapers.android.androidjavamail.SendMailTask.onProgressUpdate(SendMailTask.java:51)
thank you very much very very usefull sample
sir how to receive mails in android
i search every where but am unable to get code to receive mail code plz help me
thank you… Its working..
can u help me plz if i want to send image what i need to add in this code…
sorry my bad english i speck spanish
akshit is here very nice tutorial
could you help me to add attachment field to this code to let user send an attachment
Thanks A lot You save me ..