У меня есть простой пример 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 Он расшифровывается как: { "азп": "117395330125029916455", "ауд": "117395330125029916455", "область": "https://mail.google.com/", "эксп": "1720432913", "expires_in": "3589", "access_type": "онлайн" }
Для тех, у кого, возможно, возникнет такая же проблема: я делал это неправильно.
Я должен был использовать:
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
а затем создайте аутентификацию следующим образом:
GoogleCredentials credentials = GoogleCredentials.fromStream(new ByteArrayInputStream(SERVICE_ACCOUNT_KEY_JSON.getBytes(StandardCharsets.UTF_8)))
.createScoped(Collections.singleton(GmailScopes.GMAIL_SEND))
.createDelegated(USER_EMAIL);
Gmail gmailService = new Gmail.Builder(new NetHttpTransport(), JSON_FACTORY, new HttpCredentialsAdapter(credentials))
.setApplicationName(APPLICATION_NAME)
.build();