AuthenticationFailedException while sending mail using google service account

28 Views Asked by At

I used the below document for access token generation using OAuth 2.0 for server to server application and successfully received the token by following the document.

Now I want to send a mail using the below code with the access token created using the above document.

        String address = "smtp.gmail.com";
        Integer port = 587;
        Properties properties = new Properties();
        properties.put("mail.smtp.host", address);
        properties.put("mail.smtp.port", port.toString());
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth.mechanisms", "XOAUTH2");
        properties.put("mail.debug.auth", "true");
        Session session = Session.getInstance(properties);
        session.setDebug(true);
        try {
      
            Transport transport = session.getTransport();
            transport.connect( "client_email", "access token");
            MimeMessage message = new MimeMessage(session);  
            Address recipient = new InternetAddress("Receiver mail"); 
            Address receiver[] = {recipient};
            message.addRecipient(Message.RecipientType.TO,new InternetAddress("Receiver mail"));  
            message.setSubject("Ping");  
            message.setText("Hello, this is example of sending email  "); 
            Transport.send(message, receiver, "Client email", "access token"); 
            
        } catch (Exception e) {
            e.printStackTrace();

        }

Here Client Email is the service account mail id that we take it from the the Json file and access token is the token that i created from the above steps. But Now I recived the below exception

DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
AUTH XOAUTH2 "token"
555-5.5.2 Syntax error, goodbye. For more information, go to
555-5.5.2  https://support.google.com/a/answer/3221692 and review RFC 5321
555 5.5.2 specifications. o11-20020a170972d4cb00b001qwefc0b9f3sm9707003plg.177 - gsmtp
javax.mail.AuthenticationFailedException: 555-5.5.2 Syntax error, goodbye. For more information, go 

Can anyone please help me on this.

0

There are 0 best solutions below