由于AuthenticationException,无法使用smtp发送邮件

时间:2017-01-27 13:30:30

标签: android email authentication smtp-auth

我正在使用以下类发送邮件,但作为回应我得到了一些例外,我已粘贴在这里。用户名和密码是否正确,可能是错误的原因是什么?

代码:

package com.mailsend;

import android.util.Log;

import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
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;

public class Mail extends javax.mail.Authenticator {
    private String _user;
    private String _pass;
    private int emailType;

    private String[] _to;
    private String _from;

    private String _port;
    private String _sport;

    private String _host;

    private String _subject;
    private String _body;

    private boolean _auth;

    private boolean _debuggable;

    private Multipart _multipart;

    public Mail() {
        _host = "smtp.gmail.com"; // default smtp server
        _port = "465"; // default smtp port
        _sport = "465"; // default socketfactory port

        _user = ""; // username
        _pass = ""; // password
        _from = ""; // email sent from
        _subject = ""; // email subject
        _body = ""; // email body

        _debuggable = true; // debug mode on or off - default off
        _auth = true; // smtp authentication - default on

        _multipart = new MimeMultipart();

        MailcapCommandMap mc = (MailcapCommandMap) CommandMap
                .getDefaultCommandMap();
        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
        CommandMap.setDefaultCommandMap(mc);
    }

    public Mail(final String user, final String pass, int emailType) {
        this();

        _user = user;
        _pass = pass;
        this.emailType = emailType;
    }

    public boolean send() {
        try {
            Properties props = _setProperties();

            if (!_user.equals("") && !_pass.equals("") && _to.length > 0
                    && !_from.equals("") && !_subject.equals("")
                    && !_body.equals("")) {
                //props.put("mail.smtp.user", _from);
                Session session = Session.getInstance(props, this);
                // Session session = Session.getInstance(props, new Mail(_user,
                // _pass));
                MimeMessage msg = new MimeMessage(session);

                msg.setFrom(new InternetAddress(_from));

                InternetAddress[] addressTo = new InternetAddress[_to.length];
                for (int i = 0; i < _to.length; i++) {
                    addressTo[i] = new InternetAddress(_to[i]);
                }
                msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

                msg.setSubject(_subject);
                msg.setSentDate(new Date());

                if (emailType == 1) {
                    BodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setText(_body);
                    _multipart.addBodyPart(messageBodyPart);

                    msg.setContent(_multipart);
                } else if (emailType == 2) {
                    msg.setText(_body, "utf-8", "html");
                }

                // send email
                Transport.send(msg);
                Log.d("usm_mail", "sendind msg " + _body);

                return true;
            } else {
                return false;
            }
        }
        catch (Exception e)  { e.printStackTrace(); }
        return false;
    }

    public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);

        _multipart.addBodyPart(messageBodyPart);
    }

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(_user, _pass);
    }

    private Properties _setProperties() {
        Properties props = new Properties();

        props.put("mail.smtp.host", _host);

        if (_debuggable) {
            props.put("mail.debug", "true");
        }

        if (_auth) {
            props.put("mail.smtp.auth", "true");
        }

        props.put("mail.smtp.port", _port);
        props.put("mail.smtp.socketFactory.port", _sport);
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        return props;
    }

    // the getters and setters
    public String getBody() {
        return _body;
    }

    public void setBody(String _body) {
        this._body = _body;
    }

    public void setTo(String[] toArr) {
        // TODO Auto-generated method stub
        this._to = toArr;
    }

    public void setFrom(String string) {
        // TODO Auto-generated method stub
        this._from = string;
    }

    public void setSubject(String string) {
        // TODO Auto-generated method stub
        this._subject = string;
    }

    // more of the getters and setters �..
}

例外:

System.out: DEBUG: JavaMail version 1.4.1
I/System.out: DEBUG: not loading file: /system/lib/javamail.providers
I/System.out: DEBUG: java.io.FileNotFoundException: /system/lib/javamail.providers: open failed: ENOENT (No such file or directory)
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
I/System.out: DEBUG: !anyLoaded
I/System.out: DEBUG: not loading resource: /META-INF/javamail.providers
I/System.out: DEBUG: not loading resource: /META-INF/javamail.default.providers
I/System.out: DEBUG: failed to load any providers, using defaults
I/System.out: DEBUG: Tables of loaded providers
I/System.out: DEBUG: Providers Listed By Class Name: {com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc.,1.4.1], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc.,1.4.1], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4.1], com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4.1], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc.,1.4.1], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc.,1.4.1]}
I/System.out: DEBUG: Providers Listed By Protocol: {pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc.,1.4.1], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc.,1.4.1], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc.,1.4.1], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4.1], imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc.,1.4.1], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4.1]}
I/System.out: DEBUG: not loading resource: /META-INF/javamail.default.address.map
I/System.out: DEBUG: !anyLoaded
I/System.out: DEBUG: not loading resource: /META-INF/javamail.address.map
I/System.out: DEBUG: not loading file: /system/lib/javamail.address.map
I/System.out: DEBUG: java.io.FileNotFoundException: /system/lib/javamail.address.map: open failed: ENOENT (No such file or directory)
I/System.out: DEBUG: failed to load address map, using defaults
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
I/System.out: DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4.1]
I/System.out: DEBUG SMTP: useEhlo true, useAuth true
I/System.out: DEBUG SMTP: useEhlo true, useAuth true
I/System.out: DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
I/System.out: 220 smtp.gmail.com ESMTP s136sm11447877pgc.38 - gsmtp
I/System.out: DEBUG SMTP: connected to host "smtp.gmail.com", port: 465
I/System.out: EHLO localhost
I/System.out: 250-smtp.gmail.com at your service, [202.166.173.132]
I/System.out: 250-SIZE 35882577
I/System.out: 250-8BITMIME
I/System.out: 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
I/System.out: 250-ENHANCEDSTATUSCODES
I/System.out: 250-PIPELINING
I/System.out: 250-CHUNKING
I/System.out: 250 SMTPUTF8
I/System.out: DEBUG SMTP: Found extension "SIZE", arg "35882577"
I/System.out: DEBUG SMTP: Found extension "8BITMIME", arg ""
I/System.out: DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH"
I/System.out: DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
I/System.out: DEBUG SMTP: Found extension "PIPELINING", arg ""
I/System.out: DEBUG SMTP: Found extension "CHUNKING", arg ""
I/System.out: DEBUG SMTP: Found extension "SMTPUTF8", arg ""
I/System.out: DEBUG SMTP: Attempt to authenticate
I/System.out: AUTH LOGIN
I/System.out: 334 VXNlcm5hbWU6
I/System.out: dmVsb2Zvb2RyMUBnbWFpbC5jb20=
I/System.out: 334 UGFzc3dvcmQ6
I/System.out: eTF5MnkzeTQ=
I/System.out: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbsq
I/System.out: 534-5.7.14 FA9KEamJQo2BxbjXpwkW-oz0-yU2OUblChDH9fx85CwWNKILKOzTk4TDoV5_QoS16XYYhA
I/System.out: 534-5.7.14 EPVtOfrH8jQV1PCdWUEm5UzNG6dlEwDt61I6NX0GBl7Mox6bcf_CZbUJsb9nJBlOV8xYmn
I/System.out: 534-5.7.14 z6cleMLGilD11Ip28kdjuAd27XwUqYPS4TTjna3CwJHZD-IBL10o1TTU3JmDo_DvTEA395
I/System.out: 534-5.7.14 qcLXXeO1h58qBU8OkP1J9KQM5GUs8> Please log in via your web browser and
I/System.out: 534-5.7.14 then try again.
I/System.out: 534-5.7.14  Learn more at
I/System.out: 534 5.7.14  https://support.google.com/mail/answer/78754 s136sm11447877pgc.38 - gsmtp
W/System.err: javax.mail.AuthenticationFailedException
W/System.err:     at javax.mail.Service.connect(Service.java:319)
W/System.err:     at javax.mail.Service.connect(Service.java:169)
W/System.err:     at javax.mail.Service.connect(Service.java:118)
W/System.err:     at javax.mail.Transport.send0(Transport.java:188)
W/System.err:     at javax.mail.Transport.send(Transport.java:118)
W/System.err:     at com.mailsend.Mail.send(Mail.java:113)
W/System.err:     at com.restaurant.app.DashboardActivity$Send_Mail_Task.doInBackground(DashboardActivity.java:183)
W/System.err:     at com.restaurant.app.DashboardActivity$Send_Mail_Task.doInBackground(DashboardActivity.java:131)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err:     at java.lang.Thread.run(Thread.java:818)

2 个答案:

答案 0 :(得分:0)

您的Google帐户设置不允许通过gmail或google以外的其他外部应用程序连接到该帐户。您的凭据没问题,但是您的应用程序似乎不那么安全了。请参阅链接https://support.google.com/accounts/answer/6010255?hl=en

答案 1 :(得分:0)

而不是调用Transport.send

你可以尝试

transport = session.getTransport("smtp");
transport.connect(host, username, pass);

并检查连接呼叫的结果。如果成功,请继续

transport.sendMessage(message, message.getAllRecipients())

另一方面,你可以将它添加到你的道具

properties.put("mail.smtp.starttls.enable", "true")