Now you can Subscribe using RSS

Submit your Email

Thursday

Send Email from Android App directly without Intent

Vishal Shrestha
Sending Email from an Android app is not difficult if you want to open up another Email App that handles sending the Email. We can just achieve that by adding an ACTION_SEND intent and we can also set content type and use extras such as EXTRA_EMAIL, EXTRA_CC and more. If we start this intent, all the apps that can handle emails such as Gmail app, default Email app will be shown in a chooser dialog if you haven't chosen a default already. Then your user can easily manage the creation and sending of the email from the third party app. But that's not always the case, some times we are required to send an Email from our own App with a fixed Email address to a specific Email address, for example if we need to send a password recovery link on the click of Forgot Password, recovery link to the user should be sent by email from within our app with our own Email Address. In this post we will learn how we can send Email directly from an Android App without and Intent. So let us begin.

sending-emails-directly-from-app
Screenshot of final App of this tutorial

Steps in sending Email from Android App directly without Intent: 

 

  • We require 3 jar libraries for allowing us to send Emails, download the three libraries (LINK BELOW)
  • We create a JSSEProvider class.
  • We create a MailSender class that handles Authentication for our Email and sends Email directly without intent.
So now that we have the steps laid out, let's dig deeper on how to send Email Directly form our App, here's a sample video of the Email app that we will create:


Step 1
First of all download the 3 files- Activation.jar, Additional.jar, Mail.jar.
These are libraries that allow us to send Email in Java.
Once you've downloaded theses files, put it in the libs folder inside your app directory. If you don't have a libs folder inside your app folder, create one and place these files inside the folder.

Step 2
Now that you've copied the files in libs directory, it's time to include those libraries as dependencies. You'll need to do some changes in the app level Gradle file.  Add the following lines in you dependencies section:

compile files('libs/activation.jar')
compile files('libs/additional.jar')
compile files('libs/mail.jar')

Now you are done with libraries part and are ready to code the Email Sender App.

Step 3
Create a new class called JSSEProvider it should extend Provider class. JSSE provides a framework and an implementation for the SSL and TLS security and also provides some other functionalities like encryption and more. You can learn more about it here. Now add the following code in the class. Import all the required classes:


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;
            }
        });
}
 


Step 4
Create a class that extends javax.mail.Authentication. I've called it Gmail Sender because I'll be sending Email from one of my Gmail account. Now add the following code in the class:

 private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;

    static {
        Security.addProvider(new 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);
            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){
            Log.d("mylog", "Error in sending: " + e.toString());
        }
    }

    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");
        }
    }


Now we have all the required this are we are ready to send Email from our app. We will just create one method in our Activity and call it whenever we need to send the Email to the User. This method will contain your Email Address, your password so you can be authenticated and the email address of your recipient. Let's call this methods sendMessage():

private void sendMessage() {
        final ProgressDialog dialog = new ProgressDialog(ActivityMain.this);
        dialog.setTitle("Sending Email");
        dialog.setMessage("Please wait");
        dialog.show();
        Thread sender = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    GMailSender sender = new GMailSender("youremail", "yourpassword");
                    sender.sendMail("EmailSender App",
                            "This is the message body",
                            "youremail",
                            "your recipient's email");
                    dialog.dismiss();
                } catch (Exception e) {
                    Log.e("mylog", "Error: " + e.getMessage());
                }
            }
        });
        sender.start();
    }


Finally we have our app ready and we can call this method whenever we need to send the Email directly from the app without any intents. You can find the full source code below, Cheers!

NOTE: Gmail has disabled logging in to accounts by third party apps. You need to disable this feature of Gmail and allow logging in from any app otherwise you won't be able to login and Emails won't be sent from your account.

Full source code for Email Sender App:Download Email Sender

Vishal Shrestha / Author & Founder

A developer by profession, a born Adventurer. I mainly do Android but like to get my hands dirty with web development and a little bit of Python. I would't rather go on a Trek than a party and you can find me having a few rounds with the heavy bag to let out the steam ;)

For Business info : My Portfolio Site.

0 comments:

Post a Comment

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha