我有以下设置服务帐户:https://developers.google.com/identity/protocols/OAuth2ServiceAccount链接。
然后尝试使用以下代码发送gmail:
public static String getAccessToken(String email) throws GeneralSecurityException, IOException
{
GoogleCredential credential1 = GoogleCredential.fromStream(new FileInputStream("Project-abcd.json")) .createScoped(Collections.singleton(GMAIL_SCOPE));
System.out.println("refreshToken : "+credential1.refreshToken());
return credential1.getAccessToken();
}
public static void main(String[] args) throws Exception {
String email = "from_email";
ServiceAccountGmail sag=new ServiceAccountGmail();
String authToken = sag.getAccessToken(email);
System.out.println("OAuth TOken is : "+authToken);
OAuth2Authenticator.initialize();
SMTPTransport smtpTransport = OAuth2Authenticator.connectToSmtp("smtp.gmail.com", 587, email, authToken, true);
System.out.println("Successfully authenticated to SMTP.\n");
}
但是低于错误:
线程“main”中的异常javax.mail.AuthenticationFailedException:连接失败 在javax.mail.Service.connect(Service.java:403) 在org.serviceaccount.oauth.OAuth2Authenticator.connectToSmtp(OAuth2Authenticator.java:127) 在org.serviceaccount.oauth.ServiceAccountGmail.main(ServiceAccountGmail.java:52)
我可以获取身份验证令牌,但是当我将此传递给面向无法连接问题的connectToSmtp()
方法时。