Java 通过SMTP Gmail Oauth2发送邮件问题

Java 通过SMTP Gmail Oauth2发送邮件问题,java,smtp,gmail,smtp-auth,google-oauth,Java,Smtp,Gmail,Smtp Auth,Google Oauth,我可以通过以下方式验证SMTP 但现在的问题是我无法发送邮件。每当我尝试发送邮件时,都会出现以下错误 com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 f5sm19578172pav.22 at com.sun.mail

我可以通过以下方式验证SMTP

但现在的问题是我无法发送邮件。每当我尝试发送邮件时,都会出现以下错误

com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 f5sm19578172pav.22

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2114)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1618)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119)
    at javax.mail.Transport.send0(Transport.java:195)
    at javax.mail.Transport.send(Transport.java:124)
首先,我无法连接到本地主机,所以我向会话属性添加了几行代码,如下所示,添加到OAuth2Authenticator类,仍然成功地进行了身份验证。但是不能发送邮件

props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
我使用的是相同的会话对象和SMTP传输对象,当我第一次成功进行身份验证时,它将从OAuth2Authenticator类返回

            Message message = new MimeMessage(session);


        message.setFrom(new InternetAddress(msg.getFrom()));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(msg.getTo()));
        message.setSubject(msg.getSubject());
        message.setText(msg.getBody());

        transport.send(message);
完整调试日志

DEBUG: setDebug: JavaMail version 1.4.5
DEBUG SMTP: enable SASL
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP gj1sm1027169pbc.11 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO E6410-PC
250-mx.google.com at your service, [202.xxx.xxx.xxx]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO E6410-PC
250-mx.google.com at your service, [202.xxx.xxx.xxx]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Authenticate with SASL
DEBUG SMTP: SASL mechanisms allowed: XOAUTH2
DEBUG SMTP: SASL AUTH command trace suppressed
DEBUG SMTP SASL: Mechanisms: XOAUTH2
DEBUG SMTP SASL: SASL client XOAUTH2
DEBUG SMTP SASL: callback length: 1
DEBUG SMTP SASL: callback 0: javax.security.auth.callback.NameCallback@100ab23
DEBUG SMTP SASL: no response
Successfully authenticated to SMTP.
NOOP
250 2.0.0 OK gj1sm1027169pbc.11 - gsmtp
Is SMTP still connected: true
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: enable SASL
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP az8sm1466819pab.3 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO E6410-PC
250-mx.google.com at your service, [202.xxx.xxx.xxx]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO E6410-PC
250-mx.google.com at your service, [202.xxx.xxx.xxx]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<user@gmail.com>
530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 az8sm1466819pab.3 - gsmtp
DEBUG SMTP: got response code 530, with response: 530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 az8sm1466819pab.3 - gsmtp

RSET
250 2.1.5 Flushed az8sm1466819pab.3 - gsmtp
DEBUG SMTP: MessagingException while sending
com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 az8sm1466819pab.3 - gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2114)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1618)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119)
    at javax.mail.Transport.send0(Transport.java:195)
但反应还是一样

DEBUG: setDebug: JavaMail version 1.4.5
DEBUG SMTP: enable SASL
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP kl3sm6965596pbc.15 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO E6410-PC
250-mx.google.com at your service, [xxx.xxx.xxx.xxx]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO E6410-PC
250-mx.google.com at your service, [xxx.xxx.xxx.xxx]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
Successfully authenticated to SMTP.
token check : abcdefgFuYUBnbWFpbC5jb20BYXV0aD1CZWabcdefgSEVTNlpUVlFTUXZfblZfZ01FaDF6WWtSQ2kzb1d5RElFQ19mb2NmWG5Sam93RUlBYVJRTldfNwEB
AUTH XOAUTH2 abcdefgFuYUBnbWFpbC5jb20BYXV0aD1CZWabcdefgSEVTNlpUVlFTUXZfblZfZ01FaDF6WWtSQ2kzb1d5RElFQ19mb2NmWG5Sam93RUlBYVJRTldfNwEB
235 2.7.0 Accepted
NOOP
250 2.0.0 OK kl3sm6965596pbc.15 - gsmtp
Is SMTP still connected: true
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: enable SASL
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP vo6sm6969236pbc.8 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO E6410-PC
250-mx.google.com at your service, [xxx.xxx.xxx.xxx]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO E6410-PC
250-mx.google.com at your service, [xxx.xxx.xxx.xxx]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<user@gmail.com>
530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 vo6sm6969236pbc.8 - gsmtp
DEBUG SMTP: got response code 530, with response: 530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 vo6sm6969236pbc.8 - gsmtp

RSET
250 2.1.5 Flushed vo6sm6969236pbc.8 - gsmtp
DEBUG SMTP: MessagingException while sending
com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 vo6sm6969236pbc.8 - gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2114)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1618)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119)
    at javax.mail.Transport.send0(Transport.java:195)
    at javax.mail.Transport.send(Transport.java:124)

QUIT
221 2.0.0 closing connection vo6sm6969236pbc.8 - gsmtp
com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 vo6sm6969236pbc.8 - gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2114)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1618)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119)
    at javax.mail.Transport.send0(Transport.java:195)
    at javax.mail.Transport.send(Transport.java:124)
DEBUG:setDebug:JavaMail版本1.4.5
调试SMTP:启用SASL
调试SMTP:useEhlo true,useAuth false
调试SMTP:尝试连接到主机“SMTP.gmail.com”,端口587,isSSL false
220 mx.google.com ESMTP kl3sm6965596pbc.15-gsmtp
调试SMTP:已连接到主机“SMTP.gmail.com”,端口:587
EHLO E6410-PC
250-mx.google.com为您服务,[xxx.xxx.xxx.xxx]
250号35882577
250-8比特
250-STARTTLS
250增强状态码
调试SMTP:找到扩展名“大小”,参数“35882577”
调试SMTP:找到扩展名“8BITMIME”,参数“”
调试SMTP:找到扩展名“STARTTLS”,arg“”
调试SMTP:找到扩展名“ENHANCEDSTATUSCODES”,arg“”
STARTTLS
220 2.0.0准备启动TLS
EHLO E6410-PC
250-mx.google.com为您服务,[xxx.xxx.xxx.xxx]
250号35882577
250-8比特
250-AUTH登录普通XOAUTH XOAUTH2
250增强状态码
调试SMTP:找到扩展名“大小”,参数“35882577”
调试SMTP:找到扩展名“8BITMIME”,参数“”
调试SMTP:找到扩展名“AUTH”,arg“LOGIN PLAIN XOAUTH XOAUTH2”
调试SMTP:找到扩展名“ENHANCEDSTATUSCODES”,arg“”
已成功通过SMTP身份验证。
令牌检查:abcdefgFuYUBnbWFpbC5jb20BYXV0aD1CZWabcdefgSEVTNlpUVlFTUXZfblZfZ01FaDF6WWtSQ2kzb1d5RElFQ19mb2NmWG5Sam93RUlBYVJRTldfNwEB
通过xV0AD1CZWABCDEFGSEVTNLPUVLFTUxZFBLZFZ01FADF6WWTSQ2KZB1D5RELFQ19MB2NMWG5SAM93RULBYVJRTLDFNWeb对XOAUTH2 ABCDEFGFUYUBWFPBC5JB20进行认证
235 2.7.0接受
努普
250 2.0.0正常kl3sm6965596pbc.15-gsmtp
SMTP是否仍处于连接状态:true
调试:getProvider()返回javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,sun Microsystems,Inc]
调试SMTP:启用SASL
调试SMTP:useEhlo true,useAuth false
调试SMTP:尝试连接到主机“SMTP.gmail.com”,端口587,isSSL false
220 mx.google.com ESMTP vo6sm6969236pbc.8-gsmtp
调试SMTP:已连接到主机“SMTP.gmail.com”,端口:587
EHLO E6410-PC
250-mx.google.com为您服务,[xxx.xxx.xxx.xxx]
250号35882577
250-8比特
250-STARTTLS
250增强状态码
调试SMTP:找到扩展名“大小”,参数“35882577”
调试SMTP:找到扩展名“8BITMIME”,参数“”
调试SMTP:找到扩展名“STARTTLS”,arg“”
调试SMTP:找到扩展名“ENHANCEDSTATUSCODES”,arg“”
STARTTLS
220 2.0.0准备启动TLS
EHLO E6410-PC
250-mx.google.com为您服务,[xxx.xxx.xxx.xxx]
250号35882577
250-8比特
250-AUTH登录普通XOAUTH XOAUTH2
250增强状态码
调试SMTP:找到扩展名“大小”,参数“35882577”
调试SMTP:找到扩展名“8BITMIME”,参数“”
调试SMTP:找到扩展名“AUTH”,arg“LOGIN PLAIN XOAUTH XOAUTH2”
调试SMTP:找到扩展名“ENHANCEDSTATUSCODES”,arg“”
调试SMTP:use8bit false
邮寄地址:
530-5.5.1需要认证。了解更多信息,请访问
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 VO6SM69236PBC.8-gsmtp
调试SMTP:获取响应代码530,响应:530-5.5.1需要身份验证。了解更多信息,请访问
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 VO6SM69236PBC.8-gsmtp
RSET
250 2.1.5冲洗vo6sm6969236pbc.8-gsmtp
发送时调试SMTP:MessaginException
com.sun.mail.smtp.SMTPSendFailedException:530-5.5.1需要身份验证。了解更多信息,请访问
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 VO6SM69236PBC.8-gsmtp
在com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2114)上
在com.sun.mail.smtp.SMTPTransport.mailFrom上(SMTPTransport.java:1618)
在com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119)上
在javax.mail.Transport.send0(Transport.java:195)
在javax.mail.Transport.send(Transport.java:124)
退出
221 2.0.0闭合连接VO6SM69236PBC.8-gsmtp
com.sun.mail.smtp.SMTPSendFailedException:530-5.5.1需要身份验证。了解更多信息,请访问
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 VO6SM69236PBC.8-gsmtp
在com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2114)上
在com.sun.mail.smtp.SMTPTransport.mailFrom上(SMTPTransport.java:1618)
在com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119)上
在javax.mail.Transport.send0(Transport.java:195)
在javax.mail.Transport.send(Transport.java:124)

我想是的,它要求验证您的用户名

session=Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromUsername, password);
            }
          });
然后在代码中使用上述会话


我没有使用你提到的google链接中指定的代码,但我使用java mail api从我的gmail帐户发送电子邮件。使用上述代码进行身份验证

我认为这是在要求验证你的用户名

session=Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromUsername, password);
            }
          });
然后在代码中使用上述会话


我没有使用你提到的google链接中指定的代码,但我使用java mail api从我的gmail帐户发送电子邮件。使用上述代码进行身份验证

尝试将这些添加到你的道具配置中

  props.put("mail.smtp.auth", true);
  props.put("mail.smtp.starttls.enable", true);

尝试将这些添加到您的道具配置中

  props.put("mail.smtp.auth", true);
  props.put("mail.smtp.starttls.enable", true);

嗨,朋友,我终于能够使用OAUTH发送消息,发布我的OAuth2Authenticator源代码

/* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example;

import com.sun.mail.imap.IMAPStore;
import com.sun.mail.imap.IMAPSSLStore;
import com.sun.mail.smtp.SMTPTransport;

import java.security.Provider;
import java.security.Security;
import java.util.Properties;
import java.util.UUID;
import java.util.logging.Logger;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
* Performs OAuth2 authentication.
*
* <p>Before using this class, you must call {@code initialize} to install the
* OAuth2 SASL provider.
*/
public class OAuth2Authenticator {
 private static final Logger logger =
     Logger.getLogger(OAuth2Authenticator.class.getName());

 public static final class OAuth2Provider extends Provider {
   private static final long serialVersionUID = 1L;

   public OAuth2Provider() {
     super("Google OAuth2 Provider", 1.0,
           "Provides the XOAUTH2 SASL Mechanism");
     put("SaslClientFactory.XOAUTH2",
         "com.google.code.samples.oauth2.OAuth2SaslClientFactory");
   }
 }

 /**
  * Installs the OAuth2 SASL provider. This must be called exactly once before
  * calling other methods on this class.
  */
 public static void initialize() {
   Security.addProvider(new OAuth2Provider());
 }

 /**
  * Connects and authenticates to an IMAP server with OAuth2. You must have
  * called {@code initialize}.
  *
  * @param host Hostname of the imap server, for example {@code
  *     imap.googlemail.com}.
  * @param port Port of the imap server, for example 993.
  * @param userEmail Email address of the user to authenticate, for example
  *     {@code oauth@gmail.com}.
  * @param oauthToken The user's OAuth token.
  * @param debug Whether to enable debug logging on the IMAP connection.
  *
  * @return An authenticated IMAPStore that can be used for IMAP operations.
  */
 public static IMAPStore connectToImap(String host,
                                       int port,
                                       String userEmail,
                                       String oauthToken,
                                       boolean debug) throws Exception {
   Properties props = new Properties();
   props.put("mail.imaps.sasl.enable", "true");
   props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
   props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
   Session session = Session.getInstance(props);
   session.setDebug(debug);

   final URLName unusedUrlName = null;
   IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
   final String emptyPassword = "<your_gmail_password>";
   store.connect(host, port, userEmail, emptyPassword);
   return store;
 }

 /**
  * Connects and authenticates to an SMTP server with OAuth2. You must have
  * called {@code initialize}.
  *
  * @param host Hostname of the smtp server, for example {@code
  *     smtp.googlemail.com}.
  * @param port Port of the smtp server, for example 587.
  * @param userEmail Email address of the user to authenticate, for example
  *     {@code oauth@gmail.com}.
  * @param oauthToken The user's OAuth token.
  * @param debug Whether to enable debug logging on the connection.
  *
  * @return An authenticated SMTPTransport that can be used for SMTP
  *     operations.
  */
 public static 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", "true");
   props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
   props.put("mail.smtp.auth","true");
   props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);



   Session session = Session.getInstance(props);
   /*,
           new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("prateek.engineer@gmail.com", emptyPassword);
        }
      });*/
   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 = "<your_gmail_password>";
   transport.connect(host, port, userEmail, emptyPassword);

   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress("<your_gmail_id>"));
   message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("<recepient_emailid>"));
   message.setSubject("Test Message");
   message.setText("First Message using OAuth Protocol");
   /*SMTPTransport.send(message);*/

   Address[] add=new InternetAddress[1];
   add[0]= new InternetAddress("<recepient_emailid>");
   transport.sendMessage(message, add);

   return transport;
 }

 /**
  * Authenticates to IMAP with parameters passed in on the commandline.
  */
 public static void main(String args[]) throws Exception {
   /*if (args.length != 2) {
     System.err.println(
         "Usage: OAuth2Authenticator <email> <oauthToken>");
     return;
   }*/
   String email = "<your_gmail_id>";

   String oauthToken = "";


   initialize();

   IMAPStore imapStore = connectToImap("imap.gmail.com",
                                       993,
                                       email,
                                       oauthToken,
                                       true);
   System.out.println("Successfully authenticated to IMAP.\n");
   SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",
                                               587,
                                               email,
                                               oauthToken,
                                               true);

   System.out.println("Successfully authenticated to SMTP.");
 }
}
在您的连接到MTP(…)方法

你得到的回答是:

From: <your_email_id>
To: <recepient_eemail_id>
Subject: Test Message
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

First Message using OAuth Protocol //its message u have 
.
250 2.0.0 OK 1360312537 a1sm52630615pav.2 - gsmtp
Successfully authenticated to SMTP.
来自:
致:
主题:测试消息
MIME版本:1.0
内容类型:文本/纯文本;字符集=美国ascii码
内容传输编码:7bit
使用OAuth协议的第一条消息//它的消息u have
.
250 2.0.0正常1360312537 a1sm52630615pav.2-gsmtp
已成功通过SMTP身份验证。
嗨,朋友,我终于来了
  //create the message
  //Note that you do need to get the same session object that gets created within the connectToSmtp method.
  MimeMessage message = new MimeMessage(session);
  message.setFrom(new InternetAddress("from@gmail.com"));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@gmail.com"));
  message.setSubject("This is the Subject Line!");
  message.setText("This is actual message");

  //this was the magic line that is needed - for authentication
  transport.issueCommand("AUTH XOAUTH2 " + oauthToken, 235);

  //send the message
  transport.sendMessage(message, message.getAllRecipients());