admin管理员组文章数量:1403480
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(
";,
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
本文标签:
版权声明:本文标题:java - having problem using gmail-api ,There something wrong with Gmail.buidler , i think i'm adding credentials wrong w 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744369895a2602967.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论