0Pricing
AI Agents · บทเรียน

การเชื่อมต่อ Gmail ผ่าน API

ไลบรารีไคลเอ็นต์ Google API การยินยอม OAuth2 และการเลือกขอบเขต Gmail

การเชื่อมต่อ Gmail ผ่าน API เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

เหตุใดจึงควรใช้ Gmail API แทน SMTP

การทำงานอัตโนมัติของอีเมลแบบดั้งเดิมใช้ SMTP/IMAP แต่ Gmail API มีความสามารถมากกว่ามาก ได้แก่ การอ่านเธรด การค้นหาด้วยคำค้น การจัดการป้ายกำกับ และการส่งอีเมลพร้อมการยืนยันตัวตนอย่างครบถ้วน นอกจากนี้ยังรองรับ OAuth 2.0 ดังนั้นเอเจนต์ของคุณจึงไม่ต้องจัดเก็บรหัสผ่าน แต่เก็บเพียงโทเค็นการเข้าถึงที่จำกัดขอบเขตเท่านั้น

Gmail API เป็นส่วนหนึ่งของ Google Workspace APIs และเข้าถึงได้ผ่านไลบรารี google-api-python-client

# Install required libraries:
# pip install google-api-python-client google-auth google-auth-oauthlib

# The Gmail API lets agents:
# - List and search messages (labels, queries)
# - Read full message content and attachments
# - Send messages via OAuth (no password needed)
# - Manage labels and threads
# - Watch for new messages via push notifications

print('Gmail API is part of Google Workspace APIs')

การยืนยันตัวตน: บัญชีบริการเทียบกับการยืนยันตัวตนของผู้ใช้

Gmail API มีแนวทางการยืนยันตัวตนอยู่สองแบบ:

  • บัญชีบริการ: เหมาะที่สุดสำหรับการใช้งานในเวิร์กสเปซหรือองค์กรที่มีการมอบสิทธิ์ทั้งโดเมน โดยไม่ต้องมีการโต้ตอบกับผู้ใช้
  • OAuth ของผู้ใช้ (OAuth2 พร้อมหน้าจอขอความยินยอม): จำเป็นสำหรับบัญชี Gmail ส่วนบุคคล ผู้ใช้จะอนุญาตการเข้าถึงครั้งเดียว จากนั้นเอเจนต์จะใช้โทเค็นรีเฟรช

สำหรับการทำงานอัตโนมัติของเอเจนต์ส่วนใหญ่ บัญชีบริการเป็นตัวเลือกที่แนะนำเนื่องจากมีความน่าเชื่อถือ

# Service Account approach:
# 1. Go to Google Cloud Console -> APIs & Services -> Credentials
# 2. Create a Service Account
# 3. Download the JSON key file
# 4. In Google Workspace Admin: enable domain-wide delegation
# 5. Grant required scopes to the service account

# User OAuth approach:
# 1. Create OAuth 2.0 Client ID (Desktop or Web App type)
# 2. Download credentials.json
# 3. First run: user sees consent screen and grants access
# 4. Agent stores token.json with refresh token for subsequent runs

print('Choose service account for org automation, OAuth for personal Gmail')

โครงสร้าง JSON ของข้อมูลรับรอง OAuth2

Google จะให้ข้อมูลรับรองในไฟล์ JSON ซึ่งเอเจนต์จะโหลดเพื่อใช้ยืนยันตัวตน สำหรับ OAuth ของผู้ใช้ ไฟล์นี้คือ credentials.json ที่ดาวน์โหลดจาก Google Cloud Console ไฟล์นี้มีรหัสไคลเอนต์ ข้อมูลลับ และ URI สำหรับเปลี่ยนเส้นทาง โปรดอย่าบันทึกไฟล์นี้ลงในระบบควบคุมเวอร์ชัน

# credentials.json structure (User OAuth — Desktop app type):
# {
#   "installed": {
#     "client_id": "123456789.apps.googleusercontent.com",
#     "client_secret": "GOCSPX-abc123xyz",
#     "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"],
#     "auth_uri": "https://accounts.google.com/o/oauth2/auth",
#     "token_uri": "https://oauth2.googleapis.com/token"
#   }
# }

# service-account.json structure:
# {
#   "type": "service_account",
#   "project_id": "my-project",
#   "private_key_id": "abc123",
#   "private_key": "-----BEGIN PRIVATE KEY-----\n...",
#   "client_email": "agent@my-project.iam.gserviceaccount.com",
#   "client_id": "..."
# }

print('Store credential files outside your git repository')

ขอบเขตของ Gmail API

ขอบเขตของ OAuth จะกำหนดอย่างชัดเจนว่าเอเจนต์ของคุณเข้าถึงสิ่งใดได้บ้าง โปรดขอเฉพาะขอบเขตที่จำเป็น ซึ่งเป็นไปตามหลักสิทธิ์เท่าที่จำเป็น ขอบเขตของ Gmail มีตั้งแต่การอ่านอย่างเดียวไปจนถึงการเข้าถึงแบบเต็ม

  • gmail.readonly — อ่านอีเมลทั้งหมด
  • gmail.send — ส่งได้อย่างเดียว อ่านไม่ได้
  • gmail.modify — อ่าน ส่ง และแก้ไขป้ายกำกับ
  • gmail.compose — สร้างฉบับร่างเท่านั้น
# Gmail API scope constants
SCOPE_READONLY = 'https://www.googleapis.com/auth/gmail.readonly'
SCOPE_SEND = 'https://www.googleapis.com/auth/gmail.send'
SCOPE_MODIFY = 'https://www.googleapis.com/auth/gmail.modify'
SCOPE_COMPOSE = 'https://www.googleapis.com/auth/gmail.compose'

# Calendar scopes (often used alongside Gmail)
SCOPE_CALENDAR_READ = 'https://www.googleapis.com/auth/calendar.readonly'
SCOPE_CALENDAR_EVENTS = 'https://www.googleapis.com/auth/calendar.events'

# Combine scopes your agent actually needs
AGENT_SCOPES = [
    SCOPE_READONLY,
    SCOPE_SEND,
    SCOPE_CALENDAR_EVENTS
]
print(f'Using {len(AGENT_SCOPES)} scopes')

OAuth ของผู้ใช้: ขั้นตอนการยืนยันตัวตนครั้งแรก

เมื่อผู้ใช้เรียกใช้เอเจนต์เป็นครั้งแรก เอเจนต์จะเปิดเบราว์เซอร์เพื่อให้ผู้ใช้อนุญาต เอเจนต์จะจัดเก็บโทเค็นที่ได้ไว้ใน token.json ในการเรียกใช้ครั้งถัดไป เอเจนต์จะโหลดโทเค็นที่จัดเก็บไว้และรีเฟรชโดยอัตโนมัติ โดยไม่ต้องดำเนินการผ่านเบราว์เซอร์

from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import os

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def get_credentials(token_file='token.json', creds_file='credentials.json'):
    creds = None

    # Load existing token if available
    if os.path.exists(token_file):
        creds = Credentials.from_authorized_user_file(token_file, SCOPES)

    # Refresh or re-authenticate if needed
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())  # auto-refresh
        else:
            # Opens browser for user consent (first time only)
            flow = InstalledAppFlow.from_client_secrets_file(
                creds_file, SCOPES
            )
            creds = flow.run_local_server(port=0)
        # Save token for next run
        with open(token_file, 'w') as f:
            f.write(creds.to_json())

    return creds

การยืนยันตัวตนด้วยบัญชีบริการ

สำหรับเอเจนต์อัตโนมัติที่ทำงานโดยไม่ต้องโต้ตอบกับผู้ใช้ บัญชีบริการเป็นตัวเลือกที่เหมาะอย่างยิ่ง เอเจนต์จะยืนยันตัวตนด้วยคีย์ส่วนตัว จากนั้น สวมสิทธิ์เป็นผู้ใช้ Google Workspace ผ่านการมอบสิทธิ์ทั้งโดเมน โดยไม่ต้องมีหน้าจอขอความยินยอมและไม่ต้องใช้เบราว์เซอร์ มีเพียงไฟล์คีย์ JSON เท่านั้น

from google.oauth2 import service_account
import os

SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/gmail.send'
]

def get_service_account_credentials(impersonate_user):
    service_account_file = os.environ.get(
        'GOOGLE_SERVICE_ACCOUNT_JSON',
        'service-account.json'
    )

    credentials = service_account.Credentials.from_service_account_file(
        service_account_file,
        scopes=SCOPES
    )

    # Impersonate a real user (requires domain-wide delegation in Admin)
    delegated = credentials.with_subject(impersonate_user)
    return delegated

creds = get_service_account_credentials('agent@yourcompany.com')
print('Service account credentials ready')

การสร้างออบเจ็กต์บริการ Gmail

เมื่อมีข้อมูลรับรองแล้ว ให้ใช้ googleapiclient.discovery.build() เพื่อสร้างออบเจ็กต์บริการ Gmail นี่คือส่วนติดต่อหลักสำหรับการเรียกใช้ Gmail API ทั้งหมด โดยส่งชื่อบริการ 'gmail' และเวอร์ชัน 'v1'

from googleapiclient.discovery import build

def build_gmail_service(credentials):
    service = build(
        'gmail',
        'v1',
        credentials=credentials,
        cache_discovery=False  # avoid file warnings in some environments
    )
    return service

# Full setup: credentials -> service
creds = get_credentials()          # or get_service_account_credentials()
gmail = build_gmail_service(creds)

# Test: get user profile
profile = gmail.users().getProfile(userId='me').execute()
print('Email:', profile['emailAddress'])
print('Total messages:', profile['messagesTotal'])

การสร้างออบเจ็กต์บริการ Calendar

การตั้งค่าข้อมูลรับรองแบบเดียวกันนี้ใช้กับ Google Calendar ได้ เพียงสร้างด้วย 'calendar' และ 'v3' หากต้องใช้ทั้ง Gmail และ Calendar ในเอเจนต์เดียวกัน ให้สร้างบริการทั้งสองจากออบเจ็กต์ข้อมูลรับรองเดียวกัน

from googleapiclient.discovery import build

def build_google_services(credentials):
    gmail = build(
        'gmail', 'v1',
        credentials=credentials,
        cache_discovery=False
    )
    calendar = build(
        'calendar', 'v3',
        credentials=credentials,
        cache_discovery=False
    )
    return gmail, calendar

# Use both in one agent
creds = get_credentials()
gmail_service, calendar_service = build_google_services(creds)

# Test calendar access
cal_list = calendar_service.calendarList().list().execute()
for cal in cal_list.get('items', []):
    print(f'Calendar: {cal["summary"]}')

การจัดการข้อผิดพลาดของ Google API

ข้อผิดพลาดของ Google API จะถูกแจ้งขึ้นเป็น googleapiclient.errors.HttpError ข้อผิดพลาดนี้มีรหัสสถานะ HTTP และเนื้อหา JSON ที่มีรายละเอียดข้อผิดพลาด โปรดดักจับข้อผิดพลาดนี้เสมอ และบันทึกสถานะกับข้อความไว้เพื่อใช้แก้ไขข้อบกพร่อง

from googleapiclient.errors import HttpError
import json

def safe_gmail_call(service, user_id='me'):
    try:
        profile = service.users().getProfile(userId=user_id).execute()
        return profile
    except HttpError as e:
        status = e.resp.status
        try:
            error_body = json.loads(e.content.decode())
            message = error_body.get('error', {}).get('message', str(e))
        except Exception:
            message = str(e)

        if status == 401:
            print('AUTH ERROR: Credentials invalid or expired')
        elif status == 403:
            print(f'PERMISSION ERROR: {message}')
            print('Check scopes and domain-wide delegation settings')
        elif status == 429:
            print('QUOTA EXCEEDED: Gmail API rate limit hit')
        else:
            print(f'Gmail API error {status}: {message}')
        return None

โควตาและขีดจำกัดอัตราการเรียกใช้ของ Google API

Gmail API มีโควตาการใช้งาน โดยค่าเริ่มต้นอยู่ที่ 1 พันล้านหน่วยโควตาต่อวัน และการเรียกใช้แต่ละครั้งมีค่าใช้จ่าย 1–100 หน่วยตามการดำเนินการ การอ่านข้อความมีค่าใช้จ่ายมากกว่าการแสดงรายการ ใช้ คำขอแบบกลุ่ม และ การหน่วงเวลาเพิ่มขึ้นแบบทวีคูณเมื่อเกิดข้อผิดพลาด 429/503 เพื่อให้อยู่ภายในขีดจำกัด

import time
from googleapiclient.errors import HttpError

def gmail_call_with_retry(func, max_retries=5):
    for attempt in range(max_retries):
        try:
            return func()
        except HttpError as e:
            if e.resp.status in (429, 500, 503):
                wait = (2 ** attempt) + 1
                print(f'Quota/server error. Waiting {wait}s (attempt {attempt+1})')
                time.sleep(wait)
            elif e.resp.status == 403:
                # Check if it's a quota exceeded vs permission error
                import json
                body = json.loads(e.content.decode())
                reason = body.get('error', {}).get('errors', [{}])[0].get('reason', '')
                if reason == 'rateLimitExceeded':
                    time.sleep(2 ** attempt)
                else:
                    raise  # real permission error, don't retry
            else:
                raise
    raise Exception(f'Gmail API call failed after {max_retries} attempts')

การจัดเก็บข้อมูลรับรองอย่างปลอดภัย

โปรดอย่าบันทึก token.json, credentials.json หรือ service-account.json ลงในระบบควบคุมเวอร์ชัน เพิ่มไฟล์เหล่านี้ลงใน .gitignore ในสภาพแวดล้อมจริง ให้จัดเก็บ JSON ของบัญชีบริการไว้ในตัวแปรสภาพแวดล้อมหรือตัวจัดการข้อมูลลับ และโหลดเมื่อทำงาน

import json
import os
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def get_credentials_from_env():
    # Load service account JSON from environment variable
    sa_json = os.environ.get('GOOGLE_SERVICE_ACCOUNT_JSON')
    if not sa_json:
        raise EnvironmentError(
            'GOOGLE_SERVICE_ACCOUNT_JSON env var not set. '
            'Set it to the contents of your service-account.json'
        )

    sa_info = json.loads(sa_json)
    credentials = service_account.Credentials.from_service_account_info(
        sa_info,
        scopes=SCOPES
    )
    return credentials

# In production: export GOOGLE_SERVICE_ACCOUNT_JSON=$(cat service-account.json)
creds = get_credentials_from_env()
print('Service account loaded from env var')

แบบทดสอบสั้น ๆ: บัญชีบริการเทียบกับ OAuth ของผู้ใช้

ทดสอบความเข้าใจเกี่ยวกับวิธีการยืนยันตัวตนของ Gmail API

สรุปการเชื่อมต่อ Gmail API

ขณะนี้คุณสามารถเชื่อมต่อเอเจนต์กับ Gmail ได้แล้ว:

  • OAuth ของผู้ใช้: ใช้ InstalledAppFlow และจัดเก็บ token.json โดยรีเฟรชอัตโนมัติในการเรียกใช้ครั้งถัดไป
  • บัญชีบริการ: โหลดคีย์ JSON แล้วเรียก .with_subject(user_email) เพื่อมอบสิทธิ์
  • ขอบเขต: ขอเฉพาะขอบเขตขั้นต่ำที่จำเป็น (gmail.readonly, gmail.send, calendar.events)
  • สร้างบริการด้วย build('gmail', 'v1', credentials=creds)
  • ดักจับ HttpError สำหรับข้อผิดพลาดของ API และลองใหม่เมื่อเกิด 429/503
  • อย่าบันทึกไฟล์ข้อมูลรับรองลงในระบบควบคุมเวอร์ชัน ใช้ตัวแปรสภาพแวดล้อมในสภาพแวดล้อมจริง

คำถามที่พบบ่อย

บทเรียน “การเชื่อมต่อ Gmail ผ่าน API” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การเชื่อมต่อ Gmail ผ่าน API” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การเชื่อมต่อ Gmail ผ่าน API”

ไลบรารีไคลเอ็นต์ Google API การยินยอม OAuth2 และการเลือกขอบเขต Gmail คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การเชื่อมต่อ Gmail ผ่าน API” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การเชื่อมต่อ Gmail ผ่าน API
  2. การอ่านและส่งอีเมลด้วยโปรแกรม
  3. การสร้างและค้นหาเหตุการณ์ในปฏิทิน
  4. การสร้างตัวแทนผู้ช่วยอีเมลอย่างง่าย
← กลับไปที่ AI Agents