0

so this is my first project in spring boot (noob) , i wanted to created this gmail sending service, i got code from some repository but it's not working , i saw official documents , but they are passing credentials through json file , here i'm passing this credentials as object but it's now working , i used chatgpt and still no

can any one tell what i'm doing wrong

also i tried debugging, access token is generating , and credential object also generating but when Gmail.Builder line execute it just stop there , do nothing , no error and nothing just stop execution

@Data
@Service
public class GmailService {

    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private HttpTransport httpTransport;
    private GmailCredential gmailCredential;
    @Value("${spring.security.oauth2.client.registration.google.client-id}")
    private String clientId;
    @Value("${spring.security.oauth2.client.registration.google.client-secret}")
    private String secretKey;
    private String refreshToken;
    private String fromEmail;
    private String toEmail;


    @SneakyThrows
    public GmailService() {

        this.httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        this.gmailCredential = new GmailCredential(
                clientId,
                secretKey,
                refreshToken,
                null,
                null,
                fromEmail
        );

    }

    public boolean sendMessage(
            String subject,
            String body,
            MultipartFile attachment) throws MessagingException, IOException {

        refreshAccessToken();

        Message message = createMessageWithEmail(
                createEmail(toEmail, gmailCredential.userEmail(), subject, body));

        return createGmail()
                .users()
                .messages()
                .send(gmailCredential.userEmail(), message)
                .execute()
                .getLabelIds()
                .contains("SENT");

    }

    private Gmail createGmail() {

        TokenResponse tokenResponse = refreshAccessToken();
        Credential credential = authorize();
//        // Create GoogleCredential from the TokenResponse
//        GoogleCredential credential = new GoogleCredential.Builder()
//                .setTransport(httpTransport)
//                .setJsonFactory(JSON_FACTORY)
//                .setClientSecrets(clientId, secretKey)
//                .build()
//                .setAccessToken(tokenResponse.getAccessToken());

        return new Gmail.Builder(httpTransport, JSON_FACTORY, credential)
                .build();

    }

    private MimeMessage createEmail(
            String to,
            String from,
            String subject,
            String bodyText) throws MessagingException {

        MimeMessage email = new MimeMessage(Session.getDefaultInstance(new Properties(), null));

        email.setFrom(new InternetAddress(from));

        email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));

        email.setSubject(subject);

        email.setText(bodyText);

        return email;

    }


    private Message createMessageWithEmail(MimeMessage emailContent)
            throws MessagingException, IOException {

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        emailContent.writeTo(buffer);

        return new Message()
                .setRaw(Base64.encodeBase64URLSafeString(buffer.toByteArray()));
    }

    private Credential authorize() {

        try {

            TokenResponse tokenResponse = refreshAccessToken();

            return new Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse(
                    tokenResponse);

        } catch (Exception e) {

            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Not able to process request.");

        }

    }

    private TokenResponse refreshAccessToken() {

        RestTemplate restTemplate = new RestTemplate();

        GmailCredential gmailCredentialsDto = new GmailCredential(
                clientId,
                secretKey,
                refreshToken,
                "refresh_token",
                null,
                null
        );

        HttpEntity<GmailCredential> entity = new HttpEntity(gmailCredentialsDto);

        try {

            GoogleTokenResponse response = restTemplate.postForObject(
                    "https://www.googleapis.com/oauth2/v4/token",
                    entity,
                    GoogleTokenResponse.class);
            System.out.println("request sucess234wefull ");

            gmailCredential = new GmailCredential(
                    clientId,
                    secretKey,
                    refreshToken,
                    null,
                    response.getAccessToken(),
                    fromEmail
            );
            System.out.println("request sucessfull ");
            return response;

        } catch (Exception e) {

            e.printStackTrace();

            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Not able to process request.");

        }
    }

}


package com.lemon.worker.utils;

import lombok.Data;

import javax.annotation.Nullable;

public record GmailCredential(
        @Nullable
        String client_id,
        @Nullable
        String client_secret,
        @Nullable
        String refresh_token,
        @Nullable
        String grant_type,
        @Nullable
        String access_token,
        @Nullable
        String userEmail
) {

        public String getAccessToken() {
                return "something";
        }
}
package com.lemon.worker.utils;


import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.util.Key;

public class GoogleTokenResponse extends TokenResponse {

    @Key("expires_in")
    private Integer expiresInSeconds;
}


this error is thrown in dubug mode when Builder line executed-> throw ex.getTargetException();

    @Nullable
    public static Object invokeJoinpointUsingReflection(@Nullable Object target, Method method, Object[] args) throws Throwable {
        try {
            Method originalMethod = BridgeMethodResolver.findBridgedMethod(method);
            ReflectionUtils.makeAccessible(originalMethod);
            return coroutinesReactorPresent && KotlinDetector.isSuspendingFunction(originalMethod) ? AopUtils.KotlinDelegate.invokeSuspendingFunction(originalMethod, target, args) : originalMethod.invoke(target, args);
        } catch (InvocationTargetException ex) {
            throw ex.getTargetException(); // <----- this exception is thrown 
        } catch (IllegalArgumentException ex) {
            throw new AopInvocationException("AOP configuration seems to be invalid: tried calling method [" + String.valueOf(method) + "] on target [" + String.valueOf(target) + "]", ex);
        } catch (IllegalAccessException ex) {
            throw new AopInvocationException("Could not access method [" + String.valueOf(method) + "]", ex);
        }
    }

one thing i like to mention that access is getting generate also is in Credential credential

3
  • Please include the entire stack trace so we can see how we got to the InvocationTargetException. Commented Mar 21 at 14:55
  • @JohnWilliams hi , actually i solved the problem , refreshAccessToken(); i was calling twice , it shouldn't be called in sendMessage, that was causing the problem, i remove that now it's some how working , i don't understand the reason. and there is no stack trace during this , when bug is cause there no stack trace , it's just stop working there- so after bug whole process like paused and no further execution . only reason i was able to catch error in debug mode else , there no error shown in stack trace Commented Mar 22 at 7:30
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a minimal reproducible example. Commented Mar 24 at 13:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.