使用 Gmail API 下载附件

问题描述 投票:0回答:0

我正在尝试下载通过 gmail 从特定发件人收到的所有附件。我写了一个代码,但它不起作用,我不确定是什么问题。 OAuth 2.0 凭据的第一部分和 Gmail API 的访问令牌工作正常。

from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

creds = None
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json',
            ['https://www.googleapis.com/auth/gmail.readonly']
        )
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.json', 'w') as token:
        token.write(creds.to_json())
import base64
import os
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Set the credentials file path
creds_path = 'path/to/credentials.json'

# Set the sender email address
sender_email = '[email protected]'

# Set the directory to save attachments
attachments_dir = r'D:/bloom/'

def download_attachments():
    # Load credentials from file
    creds = Credentials.from_authorized_user_file('token.json', ['https://www.googleapis.com/auth/gmail.readonly'])

    # Create the Gmail API service
    service = build('gmail', 'v1', credentials=creds)

    # Fetch all emails from the sender
    query = 'from:' + sender_email
    try:
        response = service.users().messages().list(userId='me', q=query).execute()
        messages = response['messages']
        print(f'Total messages from {sender_email}: {len(messages)}')

        # Iterate over the messages
        for message in messages:
            msg = service.users().messages().get(userId='me', id=message['id']).execute()
            if 'parts' in msg['payload']:
                parts = msg['payload']['parts']
                for part in parts:
                    if 'filename' in part:
                        filename = part['filename']
                        if not os.path.exists(attachments_dir):
                            os.makedirs(attachments_dir)
                        attachment_path = os.path.join(attachments_dir, filename)
                        data = part['body']['data']
                        if data:
                            print(attachment_path)
                            with open(attachment_path, 'wb') as f:
                                f.write(base64.urlsafe_b64decode(data.encode('UTF-8')))
                            print(f'Saved attachment {filename} from message {msg["id"]}')
            else:
                print(f'No attachment found in the message: {msg["id"]}')
    except HttpError as error:
        print(f'An error occurred: {error}')
        messages = None

# Call the function to download attachments
download_attachments()

这是我得到的错误:PermissionError: [Errno 13] Permission denied: 'D:/bloom/'

python permissions gmail-api
© www.soinside.com 2019 - 2024. All rights reserved.