我创建了一个程序,它可以获取电子邮件中文件的附件id,然后使用Gmail获取附件。我感兴趣的文件类型是Excel文件,所以假设我得到的附件是一个.xlsx。
根据API参考 此处 我需要从响应中获取的字段是数据。我可以在C#中得到这个字段,但我被卡在了将其转化为一个excel文件。
任何Python或C#的例子都会对我很有帮助。
我知道你在Gmail里有一封附送XLSX文件的邮件,你想把它下载到你的本地文件夹里。我将假设你已经知道你的 讯息 和 附着物 标识符,如果不是这样,请原谅我,并写下评论说出来,以便我进一步帮助你。如果你已经有了标识符,这段代码会帮助你。
#!/usr/bin/env python3
# IMPORTs for Gmail API
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# IMPORTs for data manipulation
from base64 import urlsafe_b64decode
import email
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
# Gmail API configuration
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
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', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
messageID = "{MESSAGE IDENTIFIER}"
attachmentID = "{ATTACHMENT IDENTIFIER}"
# Step I - Getting the attachment
response = service.users().messages().attachments().get(
userId='me', messageId=messageID, id=attachmentID).execute()
# Step II - Manipulating the data
bytesFile = urlsafe_b64decode(response["data"])
if bytesFile[0:2] != b'PK':
raise ValueError('The attachment is not a XLSX file!')
message = email.message_from_bytes(bytesFile)
# Step III - Storing the file
open('attachment.xlsx', 'wb').write(message.get_payload(decode=True))
if __name__ == '__main__':
main()
最初的设置是为了配置Gmail服务,我从下面这部分得到的 Gmail python快速入门. 第一步是调用 .get() 方法来接收带有附件的JSON响应。该文件将在属性 data
. 之后,在第二步,代码将使用 urlsafe_b64decode
转换 data
变成一个字节对象。在继续之前,脚本将检查 魔数 来验证它是否是一个XLSX文件;如果不是,就会出现一个错误。最后,如果一切都正确,将通过使用 .message_from_bytes()
.
在第三步,也是最后一步,脚本将把信息保存为 attachment.xlsx
用这种方法 .get_payload()
. 请注意,我是如何使用 decode
的参数 Content-Transfer-Encoding
的头 8bit
. 该文件将写入本地文件夹。如果你需要我澄清什么,请不要犹豫,问我任何问题。