【问题标题】:Download google drive attachments of an email using Gmail API in python在 python 中使用 Gmail API 下载电子邮件的谷歌驱动器附件
【发布时间】:2021-10-09 07:37:42
【问题描述】:

我目前使用this solution 通过 python 使用 Gmail API 从 Gmail 下载附件。 但是,每当附件超过 25MB 时,附件就会自动上传到 Google Drive,并且文件会在邮件中链接。在这种情况下,消息中没有 attachmentId。 我只能在消息文件的“sn-p”部分看到文件名。

有什么方法可以从邮件中下载 Google 潜水附件?

here 发布了一个类似的问题,但尚未提供解决方案

【问题讨论】:

  • 你觉得怎么样?

标签: python gmail gmail-api google-workspace


【解决方案1】:

如何下载云端硬盘“附件”

所指的“附件”实际上只是一个指向云端硬盘文件的链接,因此令人困惑的是它根本不是附件,而只是文本或 HTML。

这里的问题是,由于它本身不是附件,因此您将无法通过 Gmail API 本身获取它。您需要使用 Drive API。

要使用 Drive API,您需要获取文件 ID。这将在HTML 等内容部分中。

您可以使用re 模块对HTML 内容执行findall,我使用以下正则表达式模式来识别驱动器链接:

(?<=https:\/\/drive\.google\.com\/file\/d\/).+(?=\/view\?usp=drive_web)

这是一个获取文件 ID 的示例 python 函数。它将返回一个列表。

def get_file_ids(service, user_id, msg_id):
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()
    for part in message['payload']['parts']:
        if part["mimeType"] == "text/html":
            b64 = part["body"]["data"].encode('UTF-8')
            unencoded_data = str(base64.urlsafe_b64decode(b64))
            results = re.findall(
                '(?<=https:\/\/drive\.google\.com\/file\/d\/).+(?=\/view\?usp=drive_web)',
                unencoded_data
            )
            return results

获得 ID 后,您需要调用 Drive API。

您可以按照docs 中的示例进行操作:

file_ids = get_file_ids(service, "me", "[YOUR_MSG_ID]"

for id in file_ids:
    request = service.files().get_media(fileId=id)
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print "Download %d%%." % int(status.progress() * 100)

请记住,由于您现在将使用 Drive API 和 Gmail API,因此您需要更改项目中的范围。还记得在开发者控制台中激活 Drive API,更新您的 OAuth 同意屏幕、凭据并删除本地 token.pickle 文件。

参考文献

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多