如何使用Python的Gmail API下载邮件中关联的Google Drive附件
解决方案:Gmail API 下载关联 Google Drive 大附件
你需要同时启用 Gmail API 和 Google Drive API 权限,在 OAuth2 授权环节新增https://www.googleapis.com/auth/drive.readonly作用域,确保有权限读取关联的 Drive 文件,具体操作步骤如下:
步骤1:提取邮件中的 Google Drive 文件 ID
不要仅依赖snippet字段的内容,完整解析 Gmail 消息payload下parts中的纯文本/HTML 正文内容,通过正则匹配提取 Drive 分享链接中的文件 ID:
- 标准 Drive 分享链接格式为
https://drive.google.com/file/d/[文件ID]/xxx,可以用正则r'https://drive\.google\.com/file/d/([a-zA-Z0-9_-]+)/'匹配出所有符合规则的文件 ID。 - 如果需要精准匹配目标文件,可以将匹配到的文件元数据名称和
snippet中的文件名做对比筛选。
步骤2:调用 Google Drive API 下载文件
拿到文件 ID 后,直接调用 Drive API 的媒体下载接口即可完成附件下载,Python 示例代码如下:
# 前置依赖:已安装 google-api-python-client 库,且完成 OAuth2 授权拿到 credentials 对象 from googleapiclient.discovery import build import re # 初始化 Drive 服务实例 drive_service = build('drive', 'v3', credentials=credentials) # mail_content 为从 Gmail 消息 payload 中解析出的完整正文内容 drive_id_pattern = re.compile(r'https://drive\.google\.com/file/d/([a-zA-Z0-9_-]+)/') matched_file_ids = drive_id_pattern.findall(mail_content) # 遍历下载所有匹配到的 Drive 文件 for file_id in matched_file_ids: # 先获取文件原名,用于本地存储命名 file_info = drive_service.files().get(fileId=file_id, fields='name').execute() save_name = file_info.get('name') # 下载文件二进制内容 download_request = drive_service.files().get_media(fileId=file_id) with open(save_name, 'wb') as output_file: output_file.write(download_request.execute())
注意事项
如果此前仅申请了 Gmail 相关的授权作用域,需要更新授权配置后重新获取用户令牌,否则调用 Drive API 会返回权限错误。
内容的提问来源于stack exchange,提问作者Biswankar Das
相关产品推荐
相关产品推荐

