2013-03-22 69 views
2

同時試圖連接到SMTP使用OAuth

javax.mail.MessagingException: 334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ== 

在這裏,我得到這個錯誤在android系統發送電子郵件,而無需用戶交互是我的代碼

public class GMailOauthSender 
{ 
    private Session session; 

    public SMTPTransport connectToSmtp(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception { 

     Properties props = new Properties(); 
     props.put("mail.smtp.starttls.enable", "true"); 
     props.put("mail.smtp.starttls.required", "true"); 
     props.put("mail.smtp.sasl.enable", "false"); 
     session = Session.getInstance(props); 
     session.setDebug(debug); 

     final URLName unusedUrlName = null; 
     SMTPTransport transport = new SMTPTransport(session, unusedUrlName); 
     // If the password is non-null, SMTP tries to do AUTH LOGIN. 
     final String emptyPassword = null; 
     transport.connect(host, port, userEmail, emptyPassword); 

     byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail, oauthToken).getBytes(); 
     response = BASE64EncoderStream.encode(response); 

     transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235); 

     return transport; 
    } 

    public synchronized void sendMail(String subject, String body, String user, String oauthToken, String recipients) { 
     try { 
      SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",587,user,oauthToken,true); 

      MimeMessage message = new MimeMessage(session); 
      DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain")); 
      message.setSender(new InternetAddress(user)); 
      message.setSubject(subject); 
      message.setDataHandler(handler); 

      if (recipients.indexOf(',') > 0) 
       message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); 
      else 
       message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); 

      smtpTransport.sendMessage(message, message.getAllRecipients()); 
     } catch (Exception e) { 
      Log.d("test", e.getMessage()); 
     } 
    } 
} 

我已得到一些地方在此代碼堆棧溢出。 任何幫助?

+0

試試這個,它可以幫助你。 [使用smtp發送郵件](http://hasmukhbhadani.blogspot.in/search/label/Gmail%20integration%20in%20Android)即使您有任何問題,也請讓我知道。 – Hasmukh 2013-03-22 10:27:31

+0

嗨Hashmukh感謝您給予答覆。這很好,但我想從用戶已經在手機上設置的帳戶發送電子郵件。在這種情況下,我怎樣才能在這裏得到密碼..? – praveen 2013-03-22 10:33:13

+0

這意味着谷歌在手機中設置AC時播放Ac,密碼? – Hasmukh 2013-03-22 10:46:36

回答

0

您正在接受

eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ== 

誤差進行解碼,以使用一個Base64解碼器

{"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"} 

什麼這最終含義(如隱祕作爲消息是)以下是該認證令牌你正在使用已過期。你需要使它無效,然後得到一個新的(只需再次請求令牌)。

您令牌無效的是這樣的:

mAccountManager.invalidateAuthToken("con.google", mAuthenticationToken); 

我希望這是有幫助:)