본문 바로가기
개발팁

구글 이메일 API

by 몸에배인매너 2022. 3. 29.

구글 이메일 API

import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient import errors
import base64
from email.mime.text import MIMEText


def gmail_authenticate():
    """Gmail API 의 기본사용법을 보여줍니다.
    Lists the user's Gmail labels.
    """
    # 이 값을 수정할 경우, token.json 파일을 지우세요.
    SCOPES = ['https://mail.google.com/']
    creds = None
    # token.json 파일은 사용자의 액세스 및 새로 고침 토큰을 저장하며,
    # 권한 부여 흐름이 처음 완료되면 자동으로 생성됩니다.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 사용가능한 (유효한) 자격증명 이 없으면, 사용자가 로그인하도록 합니다.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # 다음 실행을 위해 자격증명 저장
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    # Call the Gmail API
    return build('gmail', 'v1', credentials=creds)

def create_message(sender, to, subject, message_text):
    """Create a message for an email.
    Args:
        sender: 보내는 사람 이메일 주소.
        to: 받는사람 이메일 주소.
        subject: 이메일 제목.
        message_text: 이메일 내용.
    Returns:
        base64url 로 인코딩된 이메일 객체를 포함하는 객체
    """
    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('utf8')}

def send_message(service, user_id, message):
    """
    user_id: 사용자의 이메일 주소. The special value "me"
    can be used to indicate the authenticated user.
    """
    try:
        message = service.users().messages().send(userId=user_id, body=message).execute()
        print('Message Id: %s' % message['id'])
        return message
    
    except errors.HttpError as error:
        print('An error occurred: %s' % error)

def main():
    """
    service: 승인된 Gmail API 서비스 인스턴스입니다.
    message: 보낼 메시지.
    Returns:
        Sent Message.
    """
    service = gmail_authenticate()
    message = create_message("보내는 사람", "받는 사람", "제목", "내용")
    send_message(service, "me", message)
    
main()

 

API 를 사용하는 이유는 여러 사용자에게 서비스를 제공하고자 함이다

기본코드에서는 API에서 요구하는 token이 서버에 저장되기 때문에 여러사용자가 이용할 수 없게 되어있다.

그래서 고민을 해보았는데,

먼저 각 토큰을 사용자의 로컬에 저장하는 방법인데, 사용자가 토큰파일을 관리하기는 어려워 보인다.

다음으로 생각한건 DB를 만들어서 보관하는 방법인데 안전한 방법이라고 하는거 같은데 로직이 복잡해져서 간단한 방법으로 쿠키에 저장해보기로 하였다. 찾아보니 JSON 웹 토큰을 JWT 라고 한다.

 

 

'개발팁' 카테고리의 다른 글

AWS S3 (feat.Python)  (0) 2022.04.08
MySQL 사용방법 & pymysql (feat.Python)  (0) 2022.04.06
Webpack 사용방법  (1) 2022.03.27
pipenv 가상환경  (0) 2022.03.07
Visual Studio Code 세팅  (0) 2022.03.07

댓글