Javax.mail.AuthenticationFailedException

时间:2015-04-17 10:32:03

标签: java android smtp

我尝试使用Gmail smtp服务器从我的应用发送电子邮件。为此,我使用了javax库。

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

}

这是我从活动/服务发送电子邮件的方式:

private void sendEmail(String email) throws Exception{
    String from = "myemail@gmail.com";
    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;
    }
}

但每次调用conect()方法时,我都会在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)

它与autentification有关。事实上,我收到了一封来自谷歌的电子邮件,告知有人试图访问我的帐户...

1 个答案:

答案 0 :(得分:1)

以下代码对我来说很好。为此,您需要从http://code.google.com/p/javamail-android/downloads/list链接下载libarary,并从https://commons.apache.org/proper/commons-email/download_email.cgi链接下载电子邮件。删除所有其他java邮件库只添加这四个库;

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("abc@gmail.com", "abc_password"));
                email.setSSLOnConnect(true);
                email.setFrom("abc@gmail.com");
                email.setSubject("TestMail");
                email.setMsg("This is a test mail ... :-)");
                email.addTo("dhavalpatel.244@gmail.com");
                email.send();
            } catch (EmailException e) {
                e.printStackTrace();
            }

            return null;
        }

    }