본문 바로가기

개발

[Google API] Gmail API 사용법

 

 

"이메일 전송 기능을 구현하기 위해 무료로 gmail api를 사용해보자. 간단한 구현이 필요하다면 Web3forms 도 추천한다"

 

 

사용량 제한

https://developers.google.com/workspace/gmail/api/reference/quota#:~:text=Usage%20limit%20type%20Limit%20Exceeded,quota%20units%20per%20minute%20rateLimitExceeded

 

사용량 한도  |  Gmail  |  Google for Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. 의견 보내기 사용량 한도 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. Gmail API에는 API 메서드를 호

developers.google.com


1. google cloud에서 프로젝트 선택하기

구글 로그인 후 google cloud에 들어간다.

(보안 등의 이유로 개발용 구글 계정을 만드는 것을 추천한다.)

https://console.cloud.google.com/welcome

 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

 

프로젝트를 선택 ( 프로젝트가 없을 경우 새 프로젝트 를 눌러 만든다)

 

 


2. Gmail api 사용

검색에 gmail api를 치고 

사용을 누른다


3. 앱 정보 입력

다시 프로젝트를 선택하고 > OAuth 동의 화면 클릭

브랜딩 만들기로 앱 정보를 입력한다

앱 정보, 대상, 연락처 정보 등 모두 작성 후 만들기 클릭

 


4. OAuth 클리아언트 만들기

OAuth 동의 화면 > 클라이언트 에서 OAuth 클라이언트를 만들어보자

애플리케이션 유형, 이름 등을 설정해준다.

 

※ 주의

승인된 리디렉션 uri에 아래의 주소를 추가하고 저장한다.

(나중에 로컬 테스트를 위해서 하는 것!!! 포트번호는 임의로 아무거나 정해도 된다.)

https://localhost:8782

 

 

이제 OAuth 클라이언트가 생성되었다. 

client id, client passwod을 반드시 확인하고 json 다운로드도 꼭!!! 해놓자

다운받은 json은 credentials.json으로 이름을 변경한다.


6. Python 으로 이메일 전송 테스트

emailtest.

1) 의존성 설치

pip install --upgrade google-api-python-client google-auth google-auth-oauthlib

2) email 전송해보기

emailtest.py(아래 코드)와 credentials.json을 같은 폴더에 배치한다(혹은 PATH 상수를 변경할 것)

이제 아래 코드에서 SCOPES, sender, to, from, subjet 를 원하는대로 설정한다. 

python emailtest.py로 실행

 

+) Access denied 될 경우 글 맨 아래의 내용을 확인하자

 

token이 만료되었거나 처음 실행할 경우 계정 인증이 필요하다.

emailtest.py를 실행 후에 인증할 계정을 선택하고 "계속"을 누르면 token.json이 생성되고

이메일이 전송되는 것을 확인할 수 있다.

 

 

emailtest.py

import os
import base64
from email.mime.text import MIMEText

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['https://mail.google.com/']
CREDENTIALS_PATH = 'credentials.json'
TOKEN_PATH = 'token.json'


###################################################################
def create_token():
    """OAuth 인증을 진행하여 token.json을 생성"""
    if not os.path.exists(CREDENTIALS_PATH):
        raise FileNotFoundError(f"{CREDENTIALS_PATH} 파일이 존재하지 않습니다.")

    flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_PATH, SCOPES)
    creds = flow.run_local_server(port=8782)
    with open(TOKEN_PATH, 'w') as token:
        token.write(creds.to_json())
    print("token.json이 성공적으로 생성되었습니다.")


###################################################################
def get_gmail_service():
    """Gmail 서비스 객체 생성"""
    creds = None

    if os.path.exists(TOKEN_PATH):
        creds = Credentials.from_authorized_user_file(TOKEN_PATH, SCOPES)
        if creds.expired and creds.refresh_token:
            try:
                creds.refresh(Request())
                with open(TOKEN_PATH, 'w') as token_file:
                    token_file.write(creds.to_json())
            except Exception as e:
                print("토큰 갱신 실패:", e)
                creds = None

    if not creds or not creds.valid:
        print("유효한 토큰이 없습니다. 새로 인증을 진행.")
        create_token()
        return get_gmail_service()

    return build('gmail', 'v1', credentials=creds)


###################################################################
def send_test_email():
    """테스트 이메일을 발송"""
    service = get_gmail_service()

    # 이메일 내용 작성
    message = MIMEText("hello this is test")
    message['to'] = "test@gmail.com"
    message['from'] = "test@naver.com"
    message['subject'] = "this is test"

    # 인코딩
    raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
    body = {'raw': raw_message}

    # Gmail API 호출
    try:
        sent_message = service.users().messages().send(userId='me', body=body).execute()
        print("메일 전송 성공:", sent_message['id'])
    except Exception as e:
        print("메일 전송 실패:", e)

if __name__ == "__main__":
    send_test_email()

 

 


+) access denied 인증오류가 난다면 확인할 사항

1. Client > OAuth 2.0 Client IDs > 사용한 키

Authorized redirect URIshttp://localhost:8782/ 

추가했는지 확인 (혹은 원하는 포트번호로)

 

2.

OAuth 동의 화면 > 대상 탭에서 테스트 중 인지 확인하자.

테스트중이면 Add users에 테스트 사용자를 추가해주자.