본문 바로가기
dansoon-Dev/[BackEnd]

[Java] Gmail API 를 이용하여 메일 보내기

by 단순데브 2023. 3. 10.
728x90

Gmail API로 이메일을 보내려면 Gmail API를 활성화하고 Gmail 계정을 설정해야 합니다.

따라야 할 단계는 다음과 같습니다.

  1. Google Cloud Console로 이동하여 새 프로젝트를 만듭니다.
  2. 프로젝트에 Gmail API를 활성화합니다.
  3. "자격 증명 만들기" 옵션을 선택하고 "서비스 계정 키"를 선택하여 프로젝트에 대한 자격 증명을 만듭니다.
  4. 서비스 계정 키가 포함된 JSON 파일을 다운로드하고 안전한 위치에 저장합니다.
  5. 서비스 계정 이메일 주소를 적절한 권한이 있는 사용자로 추가하여 Gmail 계정을 서비스 계정과 공유합니다.

[이메일 전송을 위한 코드 작성]

이제 개발 환경을 설정하고 Gmail API를 활성화했으므로 이메일을 보내는 코드를 작성할 수 있습니다. 

 

import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
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.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Message;

public class GmailSender {

  private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
  private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
  private static final String USER_ID = "me";
  private static final String[] SCOPES = { GmailScopes.GMAIL_SEND };

  public static void main(String... args) throws IOException, GeneralSecurityException, MessagingException {
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    Credential credential = getCredentials(HTTP_TRANSPORT);

    Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME)
        .build();

    String to = "recipient@example.com";
    String subject = "Test Email";
    String bodyText = "This is a test email.";

    MimeMessage emailContent = createEmail(to, USER_ID, subject, bodyText);
    Message message = createMessageWithEmail(emailContent);
    service.users().messages().send(USER_ID, message).execute();
  }

  private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(GmailSender.class.getResourceAsStream("/credentials.json")));
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File("tokens")))
            .setAccessType("offline")
            .build();
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

  private static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);
    email.setText(bodyText);
    return email;
  }

  private static Message createMessageWithEmail(MimeMessage emailContent) throws MessagingException, IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    emailContent.writeTo(buffer);
    byte[] bytes = buffer.toByteArray();
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
  }
}
728x90

댓글