我在尝试用 python 脚本打印电子邮件时遇到问题

问题描述 投票:0回答:0
import os.path
import base64
import google.auth
from googleapiclient.discovery import build
from google.oauth2 import service_account
# Scopes to access Gmail API
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
# Path to the service account key file
SERVICE_ACCOUNT_FILE = 'service.json'
# Email address to search for
QUERY_EMAIL = '[email protected]'
# Define the Gmail API client
def get_gmail_client():
    # Load the service account credentials
    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    # Create the Gmail API client
    service = build('gmail', 'v1', credentials=credentials)
    return service 
# Main function
def main():
    # Get the Gmail API client
    service = get_gmail_client()
    # Define the query to search for incoming emails
    query = f'from: {QUERY_EMAIL}'
    try:
        # Search for the emails matching the query
        results = service.users().messages().list(userId='me', q=query).execute()
        # Print the contents of the matching emails
        for msg in results.get('messages', []):
            # Get the message ID
            msg_id = msg['id']
            # Retrieve the message data
            message = service.users().messages().get(userId='me', id=msg_id).execute()
            # Decode the message payload
            payload = message['payload']
            body = payload['body']['data']
            decoded_body = base64.urlsafe_b64decode(body).decode('utf-8')
            print(decoded_body)
    except Exception as e:
        print(f'An error occurred: {e}')
if __name__ == '__main__':
    main()
python python-2.7 google-apps-script google-api gmail-api
© www.soinside.com 2019 - 2024. All rights reserved.