我有一个简单的 Java 示例来测试与 Gmail 服务帐户的连接。问题是当我尝试连接时,它显示“555-5.5.2 语法错误,再见。有关更多信息,请访问 555-5.5.2 https://support.google.com/a/answer/3221692 并查看 RFC 5321”,我不知道出了什么问题。
我正确地从 .json 文件生成了令牌,并且属性似乎设置正确?
这很有趣,因为我通过普通用户 Gmail 帐户发送电子邮件没有任何问题......但服务帐户抛出错误。
我的代码是这样的:
public static void main(String[] args) throws IOException, MessagingException {
// Properties
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");
// Get token
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("D:/path-to-my-json.json"))
.createScoped(Collections.singleton("https://mail.google.com/"));
credentials.refreshIfExpired();
String accessToken = credentials.getAccessToken().getTokenValue();
System.out.println("Token "+accessToken);
// Session
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
// Message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
msg.setSubject("Test");
msg.setContent("this is a test email", "text/html");
// Connect
SMTPTransport transport = new SMTPTransport(session, null);
transport.connect("smtp.gmail.com", "[email protected]", null);
transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", "[email protected]", accessToken).getBytes())), 235);
transport.sendMessage(msg, msg.getAllRecipients());
}
我尝试了多种方法,但总是遇到相同的“555-5.5.2”错误。 如果我插入令牌:https://www.googleapis.com/oauth2/v3/tokeninfo?accessToken=y 它被解码为: { "azp": "117395330125029916455", “aud”:“117395330125029916455”, “范围”:“https://mail.google.com/”, "exp": "1720432913", “expires_in”:“3589”, "access_type": "在线" }
对于任何可能遇到同样问题的人...我的做法是错误的。 我应该使用: 导入 com.google.api.services.gmail.Gmail; 导入 com.google.api.services.gmail.GmailScopes;
然后以这种方式构建身份验证: GoogleCredentials 凭据 = GoogleCredentials.fromStream(new ByteArrayInputStream(SERVICE_ACCOUNT_KEY_JSON.getBytes(StandardCharsets.UTF_8))) .createScoped(Collections.singleton(GmailScopes.GMAIL_SEND)) .createDelegate(USER_EMAIL); Gmail gmailService = new Gmail.Builder(new NetHttpTransport(), JSON_FACTORY, new HttpCredentialsAdapter(credentials)) .setApplicationName(APPLICATION_NAME) .build();