Send Mail in Android without Using Intent

Posted By : Ravi Sharma | 12-Aug-2013

Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know.


Here is the xml file
 


	<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"

	    tools:context=".MainActivity"

	    android:background="@drawable/bg">

	
	    <Button

	        android:id="@+id/send"

	        android:layout_width="150dp"

	        android:layout_height="70dp"

	        android:layout_centerInParent="true"

	        android:background="@drawable/buttonclickcolor"

	        android:text="Send Mail" />

	

	</RelativeLayout>

	

Its a very basic layout with a button to send mail.

We will be using JavaMail Api to send the mail.For which you will be required to add three jars which you may download from here
https://code.google.com/p/javamail-android/downloads/list


The code involves three files

GMailSender.java
 


	package com.example.sendmail;

	

	import javax.activation.DataHandler;

	import javax.activation.DataSource;

	import javax.activation.FileDataSource;

	import javax.mail.BodyPart;

	import javax.mail.Message;

	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;	

	import java.io.ByteArrayInputStream;

	import java.io.IOException;

	import java.io.InputStream;

	import java.io.OutputStream;

	import java.security.Security;

	import java.util.Properties;
	

	public class GMailSender extends javax.mail.Authenticator {

	private String mailhost = "smtp.gmail.com";

	    private String user;

	    private String password;

	    private Session session;

	    

	    private Multipart _multipart = new MimeMultipart();

	    static {

	        Security.addProvider(new com.example.sendmail.JSSEProvider());

	    }

	

	    public GMailSender(String user, String password) {

	        this.user = user;

	        this.password = password;

	

	        Properties props = new Properties();

	        props.setProperty("mail.transport.protocol", "smtp");

	        props.setProperty("mail.host", mailhost);

	        props.put("mail.smtp.auth", "true");

	        props.put("mail.smtp.port", "465");

	        props.put("mail.smtp.socketFactory.port", "465");

	        props.put("mail.smtp.socketFactory.class",

	                "javax.net.ssl.SSLSocketFactory");

	        props.put("mail.smtp.socketFactory.fallback", "false");

	        props.setProperty("mail.smtp.quitwait", "false");

	

	        session = Session.getDefaultInstance(props, this);

	    }

	

	    protected PasswordAuthentication getPasswordAuthentication() {

	        return new PasswordAuthentication(user, password);

	    }

	

	    public synchronized void sendMail(String subject, String body,

	            String sender, String recipients) throws Exception {

	        try {

	            MimeMessage message = new MimeMessage(session);

	            DataHandler handler = new DataHandler(new ByteArrayDataSource(

	                    body.getBytes(), "text/plain"));

	            message.setSender(new InternetAddress(sender));

	            message.setSubject(subject);

	            message.setDataHandler(handler);

	            BodyPart messageBodyPart = new MimeBodyPart();

	            messageBodyPart.setText(body);

	            _multipart.addBodyPart(messageBodyPart);

	

	            // Put parts in message

	            message.setContent(_multipart);

	            if (recipients.indexOf(',') > 0)

	                message.setRecipients(Message.RecipientType.TO,

	                        InternetAddress.parse(recipients));

	            else

	                message.setRecipient(Message.RecipientType.TO,

	                        new InternetAddress(recipients));

	            Transport.send(message);

	        } catch (Exception e) {

	

	        }

	    }

	

	    public void addAttachment(String filename) throws Exception {

	        BodyPart messageBodyPart = new MimeBodyPart();

	        DataSource source = new FileDataSource(filename);

	        messageBodyPart.setDataHandler(new DataHandler(source));

	        messageBodyPart.setFileName("download image");

	

	        _multipart.addBodyPart(messageBodyPart);

	    }

	

	    public class ByteArrayDataSource implements DataSource {

	        private byte[] data;

	        private String type;

	        

	

	        public ByteArrayDataSource(byte[] data, String type) {

	            super();

	            this.data = data;

	            this.type = type;

	        }

	

	        public ByteArrayDataSource(byte[] data) {

	            super();

	            this.data = data;

	        }

	

	

	        public void setType(String type) {

	            this.type = type;

	        }

	

	        public String getContentType() {

	            if (type == null)

	                return "application/octet-stream";

	            else

	                return type;

	        }

	

	        public InputStream getInputStream() throws IOException {

	            return new ByteArrayInputStream(data);

	        }

	

	        public String getName() {

	            return "ByteArrayDataSource";

	        }

	

	        public OutputStream getOutputStream() throws IOException {

	            throw new IOException("Not Supported");

	        }

	    }

	}

	

This is the file which is most important since this allows sending the mail, checking password authentication, adding attachments. It extends javax.mail.Authenticator, Properties class is used to declare port no to be used, protocol to be used (smtp) sendMail method sets the sender, recipients, body, subject, while addAttachment, attaches a file from sdcard.

JSSEProvider.java

 

	package com.example.sendmail;

	

	import java.security.AccessController;

	import java.security.Provider;

	

	public final class JSSEProvider extends Provider {

	

	public JSSEProvider() {

	super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");

	        AccessController

	                .doPrivileged(new java.security.PrivilegedAction<Void>() {

	                    public Void run() {

	                        put("SSLContext.TLS",

	                                "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");

	                        put("Alg.Alias.SSLContext.TLSv1", "TLS");

	                        put("KeyManagerFactory.X509",

	                                "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");

	                        put("TrustManagerFactory.X509",

	                                "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");

	                        return null;

	                    }

	                });

	    }

	}

	

This class is for security permissions so that SSL content may be handled. You dont need to modify it.


MainActivity.java

 


	package com.example.sendmail;

	

	import android.os.Bundle;

	import android.app.Activity;

	import android.util.Log;

	import android.view.Menu;

	import android.view.View;

	import android.widget.Button;

	import android.widget.Toast;

	

	public class MainActivity extends Activity {

	Button send;

	

	@Override

	protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);

	setContentView(R.layout.activity_main);

	

	        send = (Button) findViewById(R.id.send);

	        send.setOnClickListener(new View.OnClickListener() {

	

	            public void onClick(View v) {

	                // TODO Auto-generated method stub

	                new Thread(new Runnable() {

	                    public void run() {

	                        try {

	                            GMailSender sender = new GMailSender(

	                                    "[email protected]",

	                                    "Can't disclose, enter your password and your email");

	

	                            sender.addAttachment(Environment.getExternalStorageDirectory().getPath()+"/image.jpg");

	                            sender.sendMail("Test mail", "This mail has been sent from android app along with attachment",

	                                    "[email protected]",

	                                    "[email protected]");

	                            

	                            

	                            

	                            

	                        } catch (Exception e) {

	                            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();

	                            

	                        }

	                    }

	                }).start();

	            }

	        });

	

	    }

	

	}



This class uses GMailSender class to set the sender email id, password.

using addAttachment method we specify path of file to be attached.

sendMail has four parameters namely subject, body text, senders name, recipients.

 

Add appropriate file path depending on device and a valid one.


The file size to be attached may be an issue since it depends on network so mail may be send later.

I have tested code for maximum of 2 MB .

also add internet permission to manifest file.

 

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

On clicking send mail button ,mail will be send along with attachment, refresh the page or wait for sometime to see the result.

Here is the output on android device.

And here is the mail snapshot.

You may download code from here

Download Code

Thanks,

Ravi Sharma

[email protected]

 

 

 

 

About Author

Author Image
Ravi Sharma

Ravi Sharma is an Android application developer with experience in Java , Titanium and Phonegap frameworks. Ravi loves drawing and PC games.

Request for Proposal

Name is required

Comment is required

Sending message..