2017-01-27 5 views
2

메일을 보내기 위해 다음 클래스를 사용하고 있지만 이에 대한 응답으로 일부 예외가 발생했습니다. 여기에 붙여 넣었습니다. 사용자 이름과 비밀번호가 정확합니다. 오류의 원인은 무엇입니까?AuthenticationException으로 인해 smtp를 사용하여 메일을 보낼 수 없습니다.

코드 :

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) 

답변

0

Google 계정 설정 Gmail 또는 Google 이외의 외부 응용 프로그램이 연결을 허용하지 않습니다. 신임 정보는 괜찮지 만 애플리케이션이 Gmail에 비해 덜 안전 해 보입니다. 당신이

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

을 시도하고 연결 호출의 결과를 확인할 수 있습니다 대신 Transport.send

호출하는 링크 https://support.google.com/accounts/answer/6010255?hl=en

+0

보안 수준이 낮은 애플리케이션이 이미 설정에서 허용이를 추가 할 수 있습니다. –

+0

메일을 루프로 보내시겠습니까? 예를 들어 100 개의 메일을 보내고 각 보내기 작업이 로그인을 수행합니까? Gmail의 상업적 계정은 일련의 로그인을 허용하지 않습니다. 한 번 로그인하여 추가 세션 작업에 동일한 세션을 사용해야합니다. 그럴 수 있니? 예를 들어 여러 개의 앱. 보내기를 수행하고 로그인을 수행하면 차단됩니까? – benchpresser

0

를 참조하십시오. 성공하면, 다른 한편으로는

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

계속, 당신은 당신의 소품

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