1

Newb here trying to trash an email from inbox with GMail Python API. Here is what I have:

 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)  

I can confirm I have several emails in the inbox from johndoe@umich.edu using web interface, but when I try to run the python script, I am getting:

 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">. 

I take it, id='from:johndoe@umich.edu' is not a valid id value. My question is how do I represent this so it is a valid id value?

Thanks

Ubaidul Khan
  • 131
  • 3
  • 13

2 Answers2

0

It looks like you are trying to user a query to determine which messages to delete, instead of an actual messageId.

I would look into using DelMessagesMatchingQuery method from the Gmail API library.

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)

then you can define the query string when calling the function

query = 'from:johndoe@umich.edu'
print(DelMessagesMatchingQuery(service, user_id, query))
vicente louvet III
  • 384
  • 1
  • 2
  • 10
0

The id value is in Message-ID from your email: enter image description here

You can see this code in your Gmail also, with "see original message" option.

Jérôme
  • 978
  • 1
  • 9
  • 22