对垃圾邮件的GMail API调用返回“无效ID值”

时间:2018-09-27 16:27:30

标签: api gmail recycle-bin

此处的Newb尝试使用GMail Python API从收件箱中删除电子邮件。这是我所拥有的:

 24   try:                                                                          
 25     service.users().messages().trash(userId='me', id='from:johndoe@umich.edu').execute()
 26     print ("Message with id: %s deleted successfully", msg_id)                  
 27   except errors.HttpError, error:                                               
 28     print ("An error occurred: %s." % error)  

我可以使用Web界面确认johndoe@umich.edu的收件箱中有几封电子邮件,但是当我尝试运行python脚本时,却得到了:

 Checking : <googleapiclient.discovery.Resource object at 0x7f04f2e93b50>
An error occurred: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/from%3Ajohndoe%40umich.edu/trash?alt=json returned "Invalid id value">. 

我接受了,id ='from:johndoe@umich.edu'不是有效的id值。我的问题是我该如何表示它,以便它是有效的id值?

谢谢

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试使用查询来确定要删除的消息,而不是实际的messageId。

我会研究使用Gmail API库中的DelMessagesMatchingQuery方法。

def DelMessagesMatchingQuery(service, user_id, query=''):
try:
    response = service.users().messages().list(userId=user_id,
                                            q=query).execute()
    messages = []
    if 'messages' in response:
        messages.extend(response['messages'])

    while 'nextPageToken' in response:
        page_token = response['nextPageToken']
        response = service.users().messages().list(userId=user_id, 
        q=query, pageToken=page_token).execute()
        messages.extend(response['messages'])
    else:
        for message in messages:
            message_id = message['id']
            delresponse = service.users().messages().trash(userId=user_id, id=message_id).execute()      
            print(delresponse)
    return messages
except errors.HttpError as error:
    print('An error occurred: %s' % error)

然后您可以在调用函数时定义查询字符串

query = 'from:johndoe@umich.edu'
print(DelMessagesMatchingQuery(service, user_id, query))