AI एजेंट · पाठ

API के ज़रिए Gmail से जुड़ना

Google API क्लाइंट लाइब्रेरी, OAuth2 सहमति और Gmail दायरा चुनना।

पाठ 1, कुल 4 में से13 चरण

API के ज़रिए Gmail से जुड़ना, CoddyKit पर AI एजेंट का एक निःशुल्क पाठ है। यह 4 में से 1वाँ पाठ है। आप नीचे पूरा पाठ निःशुल्क पढ़ सकते हैं—फिर अंतर्निहित कोड संपादक और 24/7 एआई ट्यूटर के साथ ब्राउज़र में इसका व्यावहारिक अभ्यास कर सकते हैं। यह AI एजेंट सीखने के मार्ग का हिस्सा है और आपकी प्रगति वेब तथा CoddyKit ऐप पर सिंक होती रहती है। AI एजेंट पाठ्यक्रम में कुल 4 पाठ शामिल हैं।

SMTP के बजाय Gmail API का उपयोग क्यों करें?

पारंपरिक ईमेल स्वचालन SMTP/IMAP का उपयोग करता है, लेकिन Gmail API बहुत अधिक सुविधाएँ देता है: थ्रेड पढ़ना, क्वेरी से खोज करना, लेबल प्रबंधित करना और पूर्ण प्रमाणीकरण के साथ भेजना। यह OAuth 2.0 का भी समर्थन करता है, इसलिए आपका एजेंट कभी पासवर्ड संग्रहीत नहीं करता—केवल सीमित-दायरे वाला access token रखता है।

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 के लिए प्रमाणीकरण के दो तरीके हैं:

  • सेवा खाता: डोमेन-व्यापी प्रतिनिधिमंडल के साथ Workspace या संगठनात्मक उपयोग के लिए सबसे अच्छा; उपयोगकर्ता की सहभागिता आवश्यक नहीं
  • उपयोगकर्ता OAuth (सहमति स्क्रीन के साथ OAuth2): व्यक्तिगत Gmail खातों के लिए आवश्यक; उपयोगकर्ता एक बार पहुँच देता है और एजेंट refresh token का उपयोग करता है

अधिकांश एजेंट स्वचालन के लिए विश्वसनीयता के कारण सेवा खातों को प्राथमिकता दी जाती है।

# 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')

OAuth2 प्रमाण-पत्रों की JSON संरचना

Google प्रमाणीकरण के लिए आपके एजेंट द्वारा लोड की जाने वाली प्रमाण-पत्र जानकारी एक JSON फ़ाइल में देता है। उपयोगकर्ता OAuth के लिए यह Google Cloud Console से डाउनलोड की गई credentials.json फ़ाइल होती है। फ़ाइल में आपका क्लाइंट ID, गुप्त कुंजी और रीडायरेक्ट 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 में संग्रहीत करता है। बाद में चलाने पर वह संग्रहीत टोकन लोड करके उसे अपने-आप refresh कर देता है—ब्राउज़र से संपर्क करने की आवश्यकता नहीं होती।

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 सेवा ऑब्जेक्ट बनाना

प्रमाण-पत्र मिलने के बाद Gmail सेवा ऑब्जेक्ट बनाने के लिए googleapiclient.discovery.build() का उपयोग करें। यह सभी 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 संग्रहीत करें; बाद में चलाने पर अपने-आप refresh करें
  • सेवा खाता: JSON कुंजी लोड करें और प्रतिनिधिमंडल के लिए .with_subject(user_email) कॉल करें
  • दायरे: आवश्यक न्यूनतम का अनुरोध करें (gmail.readonly, gmail.send, calendar.events)
  • build('gmail', 'v1', credentials=creds) से सेवा बनाएँ
  • API त्रुटियों के लिए HttpError पकड़ें; 429/503 पर दोबारा प्रयास करें
  • प्रमाण-पत्र फ़ाइलों को कभी कमिट न करें—उत्पादन में पर्यावरण चर का उपयोग करें
शुरुआत निःशुल्क

एआई शिक्षक के साथ AI एजेंट सीखें — निःशुल्क

अपने ब्राउज़र में वास्तविक कोड लिखें और चलाएँ, चौबीसों घंटे एआई शिक्षक से तुरंत सहायता पाएँ, और वेब या ऐप पर वहीं से शुरू करें जहाँ आपने छोड़ा था।

पाठ्यक्रम
60
पाठ
239

अक्सर पूछे जाने वाले प्रश्न

क्या “API के ज़रिए Gmail से जुड़ना” पाठ निःशुल्क है?

हाँ—“API के ज़रिए Gmail से जुड़ना” का पूरा पाठ यहाँ वेब पर निःशुल्क पढ़ा जा सकता है। इंटरैक्टिव अभ्यास (अंतर्निहित कोड संपादक और 24/7 एआई ट्यूटर) करने और AI एजेंट पाठ्यक्रम का बाकी हिस्सा अनलॉक करने के लिए CoddyKit PRO लें। AI एजेंट पाठ्यक्रम में कुल 4 पाठ शामिल हैं।

“API के ज़रिए Gmail से जुड़ना” में मैं क्या सीखूँगा?

Google API क्लाइंट लाइब्रेरी, OAuth2 सहमति और Gmail दायरा चुनना। आप ब्राउज़र में सीधे चलाए जाने वाले व्यावहारिक कोड के साथ AI एजेंट का अभ्यास करते हैं, और पाठ पूरा करते समय 24/7 एआई ट्यूटर आपके प्रश्नों के उत्तर देता है।

क्या AI एजेंट शुरू करने के लिए मुझे किसी अनुभव की आवश्यकता है?

पहले के अनुभव की आवश्यकता नहीं है। CoddyKit पर AI एजेंट शुरुआती से लेकर उन्नत शिक्षार्थियों तक सभी के लिए व्यवस्थित किया गया है, इसलिए आप यहीं से या शुरुआत से सीखना शुरू कर सकते हैं और अपनी गति से आगे बढ़ सकते हैं। यह 4 में से 1वाँ पाठ है।

“API के ज़रिए Gmail से जुड़ना” पाठ पूरा करने में कितना समय लगता है?

CoddyKit का अधिकांश पाठ लगभग 5–10 मिनट में पूरा हो जाता है। हर पाठ छोटा और संवादात्मक है, इसलिए आप लगातार प्रगति करते हैं और वेब या ऐप पर वहीं से सीखना जारी रख सकते हैं जहाँ आपने छोड़ा था।

क्या मैं इस AI एजेंट पाठ में कोड लिख और चला सकता हूँ?

हाँ। हर AI एजेंट पाठ में एक अंतर्निर्मित कोड संपादक शामिल है, जिससे आप सीधे अपने ब्राउज़र में वास्तविक कोड लिख और चला सकते हैं और तुरंत एआई प्रतिक्रिया पा सकते हैं—स्थानीय सेटअप की आवश्यकता नहीं है।

इस पाठ्यक्रम के सभी पाठ

  1. API के ज़रिए Gmail से जुड़ना
  2. प्रोग्राम के ज़रिए ईमेल पढ़ना और भेजना
  3. कैलेंडर इवेंट बनाना और खोजना
  4. सरल ईमेल सहायक एजेंट बनाना
← AI एजेंट पर वापस जाएँ