Wenn Sie Probleme verwenden, Google Mail-API zu verwenden, gibt es etwas falsch mit Google Mail.buidler, ich denke, ich

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Wenn Sie Probleme verwenden, Google Mail-API zu verwenden, gibt es etwas falsch mit Google Mail.buidler, ich denke, ich

by Anonymous » Yesterday, 07:55

Dies ist mein erstes Projekt in Spring Boot (Noob), ich wollte diesen Google Mail -Senden -Dienst erstellen, ich habe Code von einem Repository erhalten, aber es funktioniert nicht, ich habe offizielle Dokumente gesehen, aber sie geben Anmeldeinformationen durch JSON -Datei, hier übertrage ich diese Anmeldeinformationen als Objekt, aber es arbeitet jetzt. Debugging, Access Token generiert und auch Anmeldeinformationen generieren, aber wenn Google Mail.builder -Linie es ausführen, halt es nur dort an, tun Sie nichts, kein Fehler und nichts stoppen Sie die Ausführung < /p>
@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 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.");

}
}

}

< /code>
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";
}
}
< /code>
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;
}

< /code>
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(); //
one thing i like to mention that access is getting generate also is in Credential
credential

Top