반응형
1. Google API Client Library 종속성을 pom.xml 파일에 추가합니다.
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-gmail</artifactId>
<version>v1-rev20210115-1.30.9</version>
</dependency>
2. API 클라이언트 인증
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
public class GmailService {
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
public static Gmail getGmailService() throws GeneralSecurityException, IOException {
// Build the credentials
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(GmailScopes.GMAIL_LABELS));
HttpCredentialsAdapter credentialsAdapter = new HttpCredentialsAdapter(credentials);
// Build the Gmail API client
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentialsAdapter)
.setApplicationName(APPLICATION_NAME)
.build();
return service;
}
}
3. Gmail 주소 목록 가져오기.
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GmailAddressService {
public static List<String> getGmailAddresses(Gmail service) throws IOException {
List<String> gmailAddresses = new ArrayList<>();
String user = "me";
ListLabelsResponse listResponse = service.users().labels().list(user).execute();
List<Label> labels = listResponse.getLabels();
for (Label label : labels) {
if (label.getType().equals("user") && label.getName().contains("email")) {
gmailAddresses.add(label.getName());
}
}
return gmailAddresses;
}
}
반응형
'Spring Boot' 카테고리의 다른 글
[Springboot + Vimeo] vimeo 파일 업로드 구현 (0) | 2023.02.08 |
---|---|
[Springboot + AWS S3] AWS S3 파일업로드 구현 (0) | 2023.02.08 |
[Springboot] Instagram 사진 올리기 연동 구현(인스타그램 + java) (0) | 2023.02.08 |
[Springboot] Instagram 로그인 연동 구현(인스타그램 + java) (0) | 2023.02.08 |
[Springboot] Facebook 로그인 연동 구현 (0) | 2023.02.08 |