Get 429 error but dont go out limits

i am doing script which every 10 minuties does that:

from google.oauth2.credentials import Credentials

from googleapiclient.discovery import build

import base64

from datetime import datetime

from dateutil import parser

from services.uploaded_files_service import UploadedFilesService

from repositories.uploaded_files_repository import UploadedFilesRepository

from services.dropbox_config_service import DropboxConfigService

from repositories.dropbox_config_repository import DropboxConfigRepository

from send_to_dropbox import send_files_to_dropbox

from models.session import AsyncSessionLocal

import asyncio

import re

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

creds = Credentials.from_authorized_user_file(‘gmail_tokens.json’, SCOPES)

service = build(‘gmail’, ‘v1’, credentials=creds)

async def get_last_messages(uploaded_files_service: UploadedFilesService, dropbox_config_service: DropboxConfigService):

last_uploaded = await uploaded_files_service.get_last_uploaded()

messages = service.users().messages().list(userId=‘me’, maxResults=20).execute().get(‘messages’, 
)

msgs_dict = {}

for msg in messages:

msg_id = msg\['id'\]

await asyncio.sleep(1.5)

msg_data = service.users().messages().get(userId='me', id=msg_id, format='full').execute()

payload = msg_data\['payload'\]

parts = payload.get('parts', \[\])

headers = msg_data.get('payload', {}).get('headers', \[\])

date_header = next((h\['value'\] for h in headers if h\['name'\].lower() == 'date'), None)

attachments = \[\]

if date_header:

    dt = parser.parse(date_header)

    timestamp = dt.strftime("%Y-%m-%d %H:%M:%S")

else:

    timestamp = "unknown"

print(msg_id)

if str(timestamp) not in last_uploaded:

 for part in parts:

    mime_type = part.get('mimeType')

    body = part.get('body', {})

    data = body.get('data')

    html = ""


    \# HTML-содержимое

    if mime_type == 'text/html' and data:

        html = base64.urlsafe_b64decode(data).decode('utf-8', errors='replace')


    \# Вложения

    filename = part.get('filename')

    attachment_id = body.get('attachmentId')

    if filename and attachment_id:

            await asyncio.sleep(1.5)

            attachment = service.users().messages().attachments().get(

                userId='me', messageId=msg_id, id=attachment_id

            ).execute()

            file_data = base64.urlsafe_b64decode(attachment\['data'\])


            attachments.append({

                "filename": filename,

                "filedata": file_data

            })

 msgs_dict\[timestamp\] = {

        "message": html,

        "attachments": attachments

    }

print(msgs_dict.keys())

return await send_files_to_dropbox(msgs_dict, dropbox_config_service, uploaded_files_service)

async def process_new_messages():

async with AsyncSessionLocal() as session:

    uf_repository = UploadedFilesRepository(session)

    uf_service = UploadedFilesService(uf_repository)

    dc_repository = DropboxConfigRepository(session)

    dc_service = DropboxConfigService(dc_repository)

    await get_last_messages(uf_service, dc_service)

import asyncio

print(“Скрипт запущен”)

asyncio.run(process_new_messages())

This script takes 20 last messages, checks whether rhey are in database and takes their media. But after some time i get 429

googleapiclient.errors.HttpError: <HttpError 429 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=20&alt=json returned “User-rate limit exceeded. Retry after 2025-10-30T05:15:15.501Z”. Details: “[{‘message’: ‘User-rate limit exceeded. Retry after 2025-10-30T05:15:15.501Z’, ‘domain’: ‘global’, ‘reason’: ‘rateLimitExceeded’}]”>

I try after this time it says, but get this error again with new time, in average i should wait around 15 hours but it is too much

How can i avoid that??? I am sure I dont use 1000000 quotas in minute or 100 in second, as you can see I added delay before requests but it didnt help

@Дахата_ь - Please provide what Google product you are inquiring about so that we can move this post to the appropriate area of the community. The Site Feedback area is not for product type questions.

2 Likes