我正在尝试使用他们的API从gmail的电子邮件中提取附件,并在尝试插入变量时遇到意外的关键字参数。我非常习惯Javascript,这可能就是为什么我遇到这个错误并且弄错了但是这里是相关的代码块:
def main():
credentials = get_credentials()
gsa = gspread.authorize(credentials)
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
query = ['plc/trending/31day']
for x in query:
results = service.users().messages().list(userId='me', labelIds=None, q='label:' + x, pageToken=None, maxResults=1, includeSpamTrash=None).execute()
mesgid = results['messages'][0]['id']
attresults = service.users().messages().get(userId='me', id=mesgid, format=None, metadataHeaders=None).execute()
attid = attresults['payload']['parts'][1]['body']['attachmentId']
grabattachment = service.users().messages().attachments().get(userId='me', messageId = mesgid, attachmentId = attid)
答案 0 :(得分:1)
official documentation说明附件的ID名为id
,而不是attachmentId
:
grabattachment = service.users().messages().attachments().get(userId='me', messageId = mesgid, id = attid)
您可能希望缓存service.users().messages()
和更深层次的调用,例如.attachments()
,并避免每次调用这么多对象:
messages = service.users().messages()
for x in query:
results = messages.list(
userId='me', labelIds=None, q='label:' + x,
pageToken=None, maxResults=1,
includeSpamTrash=None).execute()
mesgid = results['messages'][0]['id']
attresults = messages.get(
userId='me', id=mesgid, format=None,
metadataHeaders=None).execute()
attid = attresults['payload']['parts'][1]['body']['attachmentId']
grabattachment = messages.attachments().get(
userId='me', messageId=mesgid,
attachmentId=attid)
我还强烈怀疑你最后错过了.execute()
电话。
我还有一个印象,即messages.list()
来电已包含足够的信息来检索附件,而无需单独messages.get()
来电:
messages = service.users().messages()
for x in query:
results = messages.list(
userId='me', labelIds=None, q='label:' + x,
pageToken=None, maxResults=1,
includeSpamTrash=None).execute()
attid = results['messages'][0]['payload']['parts'][1]['body']['attachmentId']
grabattachment = messages.attachments().get(
userId='me', messageId=mesgid,
attachmentId=attid).execute()
就个人而言,我仍会测试多个附件,在加载附件数据之前检查每个附件是否有文件名。