1

Sending Email in Android using JavaMail API without using the default/built-in app

Using this tutorial, I've loaded up the code into a sample android project and imported the libraries. Changed the parameters in the lines:

send.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                GMailSender sender = new GMailSender("sender@gmail.com", "sender_password");
                sender.sendMail("This is Subject", "This is Body", "sender@gmail.com", "recipient@gmail.com");
            } catch (Exception e) {
                Log.e("SendMail", e.getMessage(), e);
            }

        }
    });

Wanted to test it out and in this code, the try block of code gets executed successfully when I press the button, but I don't receive the mail, nor do I get any errors. Since there's no readme or any guidelines as to how to use this code, I have no choice but to ask what I'm doing wrong.

Just to clear the confusion, I've put the senders email instead of sender@gmail.com, same goes for password and recipient@gmail.com.

I've also added the INTERNET permission to the manifest.

Community
  • 1
  • 1

1 Answers1

0

If you want to use mailgun instead you can do it like this:

public void sendEmailInBackground(final String subject, final String body, final String... toAddress) {

    AsyncTask task = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] objects) {

            String hostname = "smpt.mailgun.org";
            int port = 25;
            String login = "login";
            String password = "password";
            String from = "from@example.com";
            AuthenticatingSMTPClient client = null;

            try {
                client = new AuthenticatingSMTPClient();
                // optionally set a timeout to have a faster feedback on errors
                client.setDefaultTimeout(10 * 1000);
                // you connect to the SMTP server
                client.connect(hostname, port);
                // you say helo  and you specify the host you are connecting from, could be anything
                client.ehlo("localhost");
                // if your host accepts STARTTLS, we're good everything will be encrypted, otherwise we're done here
                if (client.execTLS()) {

                    client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);
                    checkReply(client);

                    client.setSender(from);
                    checkReply(client);

                    String address = "";
                    if (toAddress != null) {
                        for (String to : toAddress) {
                            if(to != null && to.length() > 0) {
                                client.addRecipient(to);
                                if (address.length() == 0) {
                                    address += ",";
                                }
                                address += to;
                            }
                        }
                    }

                    if(address.length() == 0){
                        logger.warning("No address specified for mail message");
                        return null;
                    }

                    checkReply(client);

                    Writer writer = client.sendMessageData();

                    if (writer != null) {

                        SimpleSMTPHeader header = new SimpleSMTPHeader(from, address, subject);
                        writer.write(header.toString());
                        writer.write(body);
                        writer.close();
                        if (!client.completePendingCommand()) {// failure
                            throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
                        }
                    } else {
                        throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
                    }
                } else {
                    throw new IOException("STARTTLS was not accepted " + client.getReply() + client.getReplyString());
                }
            } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) {
                logger.severe("Error sending email",e);
            } finally {
                if (client != null) {
                    try {
                        client.logout();
                        client.disconnect();
                    } catch (Exception e) {
                        logger.warning("Error closing email client: " + e.getMessage());
                    }
                }
            }
            return null;
        }
    };

    task.execute();
}

private static void checkReply(SMTPClient sc) throws IOException {

    if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
        throw new IOException("Transient SMTP error " + sc.getReplyString());
    } else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
        throw new IOException("Permanent SMTP error " + sc.getReplyString());
    }
}
nasch
  • 5,330
  • 6
  • 31
  • 52