DevOps
  • Introduction
  • Setting
    • Terminal
      • Tmux
    • WSL+Ubuntu
    • [NeoVIM]
      • install & 활용방법
      • error 처리
      • LazyVIM
        • install & 활용방법
    • ssh
    • mysql
    • package관리
  • Fundamental(basic)
    • Network
      • https
  • [GitOps]
    • [SCM]
      • [Github]
        • center-managed
      • bitbucket
      • AWS-codeCommit
  • roadmap
    • devops
    • kubernetes
    • AWS
    • MLOPS
  • Cloud
    • [AWS]
      • aws sso script
      • tagging 자동화
      • 동일cidr에서 VPC 연결
      • 무중단서비스를 위한 고려사항
    • [GCP]
      • [GCP] GCP의 VPC
      • [GCP] GCP의 ALB
      • [GCP] OIDC와 OAUTH를 활용한 github action
      • [GCP] Composer 설명
      • [GCP] gmail-api
      • [GCP] DataLake
      • [GCP] Cloud 관리형 계정&role
      • [[GCP] private환경
        • DNS 설정으로 google api 및 colab-notebook 사용 하기
        • intelligence 설정으로 google api 및 colab-notebook 사용 하기
  • [kubernetes]
    • [cloud 기반]
      • csr
  • InfraAsCode
    • terraform
  • 코드로 그리는 다이어그램
    • CodeAsDiagram
      • example
    • Mermaid
    • PDFtoImage
  • AutoMation
  • [ETC]
    • Magic_Trackpad Window설치
Powered by GitBook
On this page
  • 목차
  • Code
  • 인증 절차를 포함한 완성된 코드
  • 제약 사항
  1. Cloud
  2. [GCP]

[GCP] gmail-api

목차

일단 발신자 주소 변경에 굉장히 엄격한 기준이 적용 되어 상용(Product)으로는 쓰기 어렵다고 판단하였으나 자사 도메인으로 보내는 메일 주소라던가 조건이 맞는다면 한번쯤은 시도 해볼만한 가치가 있을것 같기도 하다

  • envrioment

    • GWS mail account

    • GCP oauth : client.json

  • Authentication & Authorization

  • Security & DNS

    • DKIM

    • SPF

    • SSL Cert

  • code

  • 제약사항

    • mail send user config

      • app Engine -> config -> email sender

Code

send_mail() function 예제

send_mail() function

    mail.send_mail(sender=sender_address,
                 to="Albert Johnson <Albert.Johnson@example.com>",
                 subject="Your account has been approved",
                 body="""Dear Albert:

Your example.com account has been approved.  You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.

Please let us know if you have any questions.

The example.com Team
""")
EmailMessage.send() function 예제

EmailMessage.send() function

    message = mail.EmailMessage(
      sender=sender_address,
      subject="Your account has been approved")

  message.to = "Albert Johnson <Albert.Johnson@example.com>"
  message.body = """Dear Albert:

Your example.com account has been approved.  You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.

Please let us know if you have any questions.

The example.com Team
"""
  message.send()

인증 절차를 포함한 완성된 코드

  • 메일 발신용 test code

  • oauth로 생성한 client와 json 파일을 경로에 잘 넣어준다.

    • kth-desktop-client-secret.json

import os
import base64
from email.mime.text import MIMEText
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

# Gmail API의 범위 설정
SCOPES = ['https://www.googleapis.com/auth/gmail.send']

def send_email():
    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(
                'kth-desktop-client-secret.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # 자격 증명을 저장
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    # Gmail API 서비스 생성
    service = build('gmail', 'v1', credentials=creds)

    # 이메일 메시지 생성
    message = MIMEText('This is a test email from Python!')
    message['to'] = 'kimutae@naver.com'
    message['from'] = 'kth@mydata.re.kr'
    message['subject'] = 'Test Email'
    raw = base64.urlsafe_b64encode(message.as_bytes()).decode()

    # 이메일 전송
    try:
        message = (service.users().messages().send(userId="me", body={'raw': raw})
                   .execute())
        print(f'Message Id: {message["id"]}')
    except Exception as error:
        print(f'An error occurred: {error}')

if __name__ == '__main__':
    send_email()

제약 사항


한도
용량

발신 메일 메시지 최대 크기(첨부파일 포함)

31.5MB

수신 메일 메시지 최대 크기(첨부파일 포함)

31.5MB

수신자가 관리자인 경우의 최대 메시지 크기

16KB

승인된 최대 발신자 수

50

  • 모든 대량 이메일의 발신자는 같아야 합니다. Mail API 함수를 호출하여 이메일을 보내는 경우, 사용자가 지정하는 발신자와 일치하도록 From 헤더가 설정됩니다.

  • 발신자 주소는 Google Workspace 도메인의 계정이어야 합니다. 도메인이 아직 무료 체험 기간 중이거나 사용자가 6명 미만인 경우, 스팸으로 표시된 이메일을 너무 많이 보내는 Google 계정이 일시적으로 중지될 수 있습니다. 이 경우 Mail API가 Unauthorized sender 오류 메시지와 함께 예외를 발생시킵니다.

  • App Engine을 사용하여 보내는 경우, G Suite 도메인이 필요한 DKIM으로 이메일에 서명합니다. 스팸 발송자가 메일 발신자의 주소를 위장하지 못하도록 SPF 레코드를 게시합니다. SPF가 메일 발신자의 DNS 레코드에 게시된 IP 주소에서 이메일이 보내진 것인지 확인합니다. App Engine의 메일 발신자는 apphosting.bounces.google.com 도메인에 있으므로, SPF 레코드를 사용하여 App Engine의 이메일이 배달되어야 하는지 여부를 결정하지 못할 수도 있습니다.


Previous[GCP] Composer 설명Next[GCP] DataLake

Last updated 8 months ago