masmic
masmic

Reputation: 3564

Javax.mail.AuthenticationFailedException

I'm trying to send an email from my app using the Gmail smtp server. To do this, I'm using javax libraries.

MailSender.java

public class MailSender {

final String emailPort = "587";// gmail's smtp port for tls
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";

String fromEmail;
String fromPassword;
String toEmail;
String emailSubject;
String emailBody;

Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;

public MailSender() {

}

public MailSender(String fromEmail, String fromPassword, String toEmail, String emailSubject, String emailBody) {
    this.fromEmail = fromEmail;
    this.fromPassword = fromPassword;
    this.toEmail = toEmail;
    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("MAIL_SENDER", "Mail server properties set.");
}

public MimeMessage createEmailMessage() throws AddressException, MessagingException, UnsupportedEncodingException {

    mailSession = Session.getInstance(emailProperties, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromEmail, fromPassword);
        }
    });
    emailMessage = new MimeMessage(mailSession);

    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    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("MAIL_SENDER", "Email Message created.");

    return emailMessage;
}

public void sendMail() throws AddressException, MessagingException {

    Transport transport = mailSession.getTransport("smtp");
    transport.connect(emailHost, fromEmail, fromPassword);
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();

    Log.i("MAIL_SENDER", "Email sent successfully.");
}

}

This is how I send email from activity/service:

private void sendEmail(String email) throws Exception{
    String from = "[email protected]";
    String pass = "mypass";
    String to = email;
    String subject = getString(R.string.email_subject);
    String body = location_link;

    sendMailTask task = new sendMailTask();
    task.execute(from, pass, to, subject, body);
}

private class sendMailTask extends AsyncTask<Object, Object, Object> {

    @Override
    protected Object doInBackground(Object... args) {
        try {
            MailSender mail = new MailSender(args[0].toString(),
                    args[1].toString(), args[2].toString(), args[3].toString(),
                    args[4].toString());
            mail.createEmailMessage();
            mail.sendMail();
        }catch (Exception e) {
            Log.e("EMAIL", e.getMessage(), e);
        }
        return null;
    }
}

But each time it calls the conect() method, I get this error in LogCat:

04-17 12:18:05.996: E/EMAIL(4160): javax.mail.AuthenticationFailedException
04-17 12:18:05.996: E/EMAIL(4160):  at javax.mail.Service.connect(Service.java:319)
04-17 12:18:05.996: E/EMAIL(4160):  at javax.mail.Service.connect(Service.java:169)
04-17 12:18:05.996: E/EMAIL(4160):  at com.myapp.mail.MailSender.sendMail(MailSender.java:82)
04-17 12:18:05.996: E/EMAIL(4160):  at com.myapp.TrackingService$sendMailTask.doInBackground(TrackingService.java:380)
04-17 12:18:05.996: E/EMAIL(4160):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-17 12:18:05.996: E/EMAIL(4160):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-17 12:18:05.996: E/EMAIL(4160):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-17 12:18:05.996: E/EMAIL(4160):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-17 12:18:05.996: E/EMAIL(4160):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-17 12:18:05.996: E/EMAIL(4160):  at java.lang.Thread.run(Thread.java:841)

It has something to do with the autentification. In fact, I have received an email from google in my account telling that someone has tried to access my account...

Upvotes: 0

Views: 1997

Answers (1)

Dhaval Patel
Dhaval Patel

Reputation: 10299

Below Code is working fine for me. For that you need to download libarary from http://code.google.com/p/javamail-android/downloads/list link and commons-email from https://commons.apache.org/proper/commons-email/download_email.cgi link. Remove all other java mail library add these four library only;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

private class MailClass extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... params) {
            try {
                Email email = new SimpleEmail();
                email.setHostName("smtp.googlemail.com");
                email.setSmtpPort(465);
                email.setAuthenticator(new DefaultAuthenticator("[email protected]", "abc_password"));
                email.setSSLOnConnect(true);
                email.setFrom("[email protected]");
                email.setSubject("TestMail");
                email.setMsg("This is a test mail ... :-)");
                email.addTo("[email protected]");
                email.send();
            } catch (EmailException e) {
                e.printStackTrace();
            }

            return null;
        }

    }

Upvotes: 1

Related Questions