Python 使用 Google API 转发 gmail 邮件

Python forward a gmail message using Google API

提问人:Muriel 提问时间:11/17/2023 最后编辑:Muriel 更新时间:11/17/2023 访问量:34

问:

我正在尝试使用 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赞 Alastair McCormack 11/17/2023 #1

gmail API (https://developers.google.com/gmail/api/reference/rest/v1/users.messages#Message) 的文档表明,每封邮件都是邮件类型。每条消息都有一个包含对象的对象。 然后有,你可能想要解析。PayloadMessagePartMessagePartbodyparts

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

如果您只是转发邮件,您可能只想提取并传递它。Message['raw']

评论

0赞 Muriel 11/17/2023
感谢@Alastair麦科马克。是的,我现在设法按照您建议的方式实施了它。我想我不明白的是为什么我从 gmail 下载的电子邮件不是邮件类型。非常感谢您的意见!