Send Email On Button Click – Without Launching Email Chooser

Sending email in Android is always very easy. We just need to call the email intent and create email chooser and that is it. As soon as you run the app and try to send email you will be asked to select the email application by which you wish to send email such as yahoo, gmail etc.

 Today in this tutorial we will custom build an email application using GMail SMTP and JavaMail API. Using GMail’s SMTP server to send email is very simple and easy to do. We need to use the ported version of JavaMail for Android. The only thing we must have to get this app run is an email id created from GMail.

Download the jar files from the link above and add them as library in your project. Apart from that e only create 2 more java file with our main activity. Follow the steps described below to create an Android app for sending Email using GMail:

Step1: Create a new android project in your android IDE.

Step2: Add the three libraries listed below to your project:

1.) mail.jar

2.) activation.jar

3.) additional.jar

you can download them from this link also.

Step3:  Create and write following into Mail.java:

 

package com.example.smtpemailsender;

import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;

private String[] _to;
private String _from;

private String _port;
private String _sport;

private String _host;

private String _subject;
private String _body;

private boolean _auth;

private boolean _debuggable;

private Multipart _multipart;

public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port

_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body

_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on

_multipart = new MimeMultipart();

// There is something wrong with MailCap, javamail can not find a handler for the multipart
// /mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}

public Mail(String user, String pass) {
this();

_user = user;
_pass = pass;
}

public boolean send() throws Exception {
Properties props = _setProperties();

if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") &&
!_subject.equals("") && !_body.equals("")) {

Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("youremail@gmail","password");
}
});
SMTPAuthenticator authentication = new SMTPAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
.getDefaultInstance(props, authentication));
msg.setFrom(new InternetAddress(_from));

InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

msg.setSubject(_subject);
msg.setSentDate(new Date());

// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);

// Put parts in message
msg.setContent(_multipart);

// send email
String protocol = "smtp";
props.put("mail." + protocol + ".auth", "true");
Transport t = session.getTransport(protocol);
try {
t.connect("smtp.gmail.com","youremail@gmail","password");
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}

return true;
} else {
return false;
}
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}

private Properties _setProperties() {
Properties props = new Properties();

props.put("mail.smtp.host", _host);

if(_debuggable) {
props.put("mail.debug", "true");
}

if(_auth) {
props.put("mail.smtp.auth", "true");
}

props.put("mail.smtp.port", _port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.ssl.enable",true);

return props;
}

// the getters and setters
public String getBody() {
return _body;
}

public void setBody(String _body) {
this._body = _body;
}
public void setTo(String[] to) {
this._to = to;
}
public void setFrom(String from) {
this._from = from;
}
public void setSubject(String subject) {
this._subject = subject;
}
}

 

 

Step4: Create and write following into SMTPAuthenticator.java:

 

package com.example.smtpemailsender;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class SMTPAuthenticator extends Authenticator {
public SMTPAuthenticator() {

super();
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = "youremail@gmail";
String password = "password";
if ((username != null) && (username.length() > 0) && (password != null)
&& (password.length() > 0)) {

return new PasswordAuthentication(username, password);
}

return null;
}
}

 

 

Step5: Write following into main layout:

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_toEndOf="@+id/textView"
android:layout_marginTop="102dp" />

</RelativeLayout>

 

 

Step6: Add INTERNET permission into your manifest.

 

<uses-permission android:name="android.permission.INTERNET"/>

 

 

Step7: Write following into your main activity:

 

package com.example.smtpemailsender;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import javax.mail.MessagingException;
public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addImage = (Button) findViewById(R.id.button);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SendMail().execute("");
}
});
}
private class SendMail extends AsyncTask<String, Integer, Void> {

private ProgressDialog progressDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Sending mail", true, false);
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}

protected Void doInBackground(String... params) {
Mail m = new Mail("youremail@gmail", "password");

String[] toArr = {"toemail@gmail", "youremail@gmail"};
m.setTo(toArr);
m.setFrom("youremail@gmail");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");

try {
if(m.send()) {
Toast.makeText(MainActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

 

 

Step8: Run to check output

smtp1

smtp2

Leave a Comment: