Python 使用 Google API 转发 Gmail 消息

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

我正在尝试使用 Google 的 API 客户端转发消息。为了做到这一点,我正在阅读消息,修改它,然后想发送它,但我遇到了一个问题,我下载的消息类型错误,并且我不知道如何对其进行编码。这是我的代码:

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import os
import base64
from datetime import datetime
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.send']

creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
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(               
            # your creds file here. Please create json file as here https://cloud.google.com/docs/authentication/getting-started
            'credentials.json', SCOPES)
        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())

    
service = build('gmail', 'v1', credentials=creds)
results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
messages = results.get('messages',[]);


message = messages[0]
msg = service.users().messages().get(userId='me', id=message['id']).execute()
print(type(msg))

msg['To'] = '[email protected]'

encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
create_message = {"raw": encoded_message}

message = (service.users().messages().send(userId='me', body=body).execute())

输出:

<class 'dict'>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[57], line 32
     28 print(type(msg))
     30 msg['To'] = '[email protected]'
---> 32 encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
     33 create_message = {"raw": encoded_message}
     35 message = (service.users().messages().send(userId='me', body=body).execute())

AttributeError: 'dict' object has no attribute 'as_bytes'

有谁知道如何对下载的消息对象(字典)进行编码?

python gmail-api urlencode
1个回答
0
投票

gmail API 的文档 (https://developers.google.com/gmail/api/reference/rest/v1/users.messages#Message) 建议每条消息都是 Message 类型。每条消息都有一个

Payload
对象,其中包含一个
MessagePart
对象。
MessagePart
然后有
body
parts
,您可能想要解析它们。

您也可以通过将

Message['raw']
传递给 Python 的
email.parser.Parser
类来取得一些成功,这将提供一种更 Pythonic 的方式来访问电子邮件的各个部分,同时提供正确的字符串解码。

如果您只是转发消息,您可能只想提取

Message['raw']
并将其传递。

© www.soinside.com 2019 - 2024. All rights reserved.