AI Email Automation 2026: GPT-4 + Gmail API for Smart Inbox Management

Automatically classify, summarize, and draft replies to emails using AI

返回教程列表
进阶35 分钟

AI Email Automation 2026: GPT-4 + Gmail API for Smart Inbox Management

Automatically classify, summarize, and draft replies to emails using AI

Build AI email automation with GPT-4 and Gmail API. Covers email classification, priority scoring, auto-draft generation, and routing—saving hours of inbox management weekly.

email automationgmailgpt-4automationproductivity

AI Email Automation 2026: GPT-4 + Gmail API for Smart Inbox Management

Use AI to automatically categorize, respond to, and manage your email inbox.

What You Can Automate

  • Auto-classify emails (support, sales, spam, urgent)
  • Generate draft replies for common request types
  • Extract action items from email threads
  • Route emails to the right team member
  • Summarize long email threads
  • Setup: Gmail API

    bash
    pip install google-auth google-auth-oauthlib google-api-python-client openai
    

    python
    from googleapiclient.discovery import build
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.oauth2.credentials import Credentials
    import base64
    import os

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

    def get_gmail_service(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) if not creds or not creds.valid: flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.json', 'w') as f: f.write(creds.to_json()) return build('gmail', 'v1', credentials=creds)

    Reading Emails

    python
    from openai import OpenAI

    openai = OpenAI() service = get_gmail_service()

    def get_unread_emails(max_results: int = 10): results = service.users().messages().list( userId='me', labelIds=['INBOX', 'UNREAD'], maxResults=max_results ).execute() emails = [] for msg in results.get('messages', []): email = service.users().messages().get(userId='me', id=msg['id'], format='full').execute() headers = {h['name']: h['value'] for h in email['payload']['headers']} body = '' if 'parts' in email['payload']: for part in email['payload']['parts']: if part['mimeType'] == 'text/plain' and 'data' in part['body']: body = base64.urlsafe_b64decode(part['body']['data']).decode() break emails.append({ 'id': msg['id'], 'from': headers.get('From', ''), 'subject': headers.get('Subject', ''), 'body': body[:2000] # Truncate for token limits }) return emails

    AI Email Classification

    python
    import json

    def classify_email(email: dict) -> dict: r = openai.chat.completions.create( model='gpt-4o-mini', messages=[{ 'role': 'user', 'content': f'Classify this email. Return JSON with fields: ' f'category (support/sales/spam/internal/urgent/newsletter), ' f'priority (high/medium/low), ' f'sentiment (positive/neutral/negative), ' f'summary (one sentence).\n\n' f'From: {email["from"]}\n' f'Subject: {email["subject"]}\n' f'Body: {email["body"]}' }], response_format={'type': 'json_object'} ) return json.loads(r.choices[0].message.content)

    Process all unread emails

    emails = get_unread_emails(20) for email in emails: classification = classify_email(email) print(f'{email["subject"]}: {classification["category"]} ({classification["priority"]})') print(f' Summary: {classification["summary"]}')

    Auto-Generate Reply Drafts

    python
    def generate_reply(email: dict, context: str = '') -> str:
        r = openai.chat.completions.create(
            model='gpt-4o',
            messages=[{
                'role': 'system',
                'content': 'You are an professional email assistant. '
                           'Write clear, concise, professional email replies. '
                           'Match the tone of the original email.'
            }, {
                'role': 'user',
                'content': f'Write a reply to this email.\n\n'
                           f'Original email:\n'
                           f'From: {email["from"]}\n'
                           f'Subject: {email["subject"]}\n'
                           f'Body: {email["body"]}\n\n'
                           f'Context/instructions: {context or "Be helpful and professional."}'
            }]
        )
        return r.choices[0].message.content

    def save_draft(service, email_id: str, reply_text: str): original = service.users().messages().get(userId='me', id=email_id, format='full').execute() headers = {h['name']: h['value'] for h in original['payload']['headers']} import email.mime.text msg = email.mime.text.MIMEText(reply_text) msg['To'] = headers.get('From', '') msg['Subject'] = 'Re: ' + headers.get('Subject', '') msg['In-Reply-To'] = headers.get('Message-Id', '') raw = base64.urlsafe_b64encode(msg.as_bytes()).decode() service.users().drafts().create( userId='me', body={'message': {'raw': raw, 'threadId': original['threadId']}} ).execute()

    Conclusion

    AI email automation saves hours per week for knowledge workers. Start with classification, then add auto-draft generation for high-volume request types. Always review AI-generated drafts before sending in production.

    相关工具

    openaigooglepython