Search code examples
pythonpython-2.7while-looppollinggmail-api

Using a function to grab links from emails, how can I poll this function effectively?


I have created a function in Python that (via the GMail API) will find an email sent to a specific email address (gmail alias), with a certain subject line and then pull information out of the message.

This function will only return something if it is successful, and it will return a string. I have 3 error catching statements eg.

try:
    gmail_service.users().messages().trash(userId='me', id=message['id']).execute() 
    print 'Message with id: %s trashed successfully.' % message['id']
except errors.HttpError, error:
    print 'Could not trash ' + message['id'] + ': %s' % error

The code for my polling is:

def check_Mail(self, recipient="", loopfor=0):
    print("Loop start! loopfor = " + str(loopfor))
    while loopfor > 1:
        if get_Mail(recipient) is None:
            loopfor -= 5
            print(str(loopfor) + " seconds left in loop")
            time.sleep(5)
        else:
            print("Woot, we have mail!")
            loopfor = 0
            print(get_Mail(recipient))
            #return get_Mail(recipient)

I am calling the check_Mail like so: check_Mail("[email protected]", 30) but the result of this method is the ouput Loop start! loopfor = 0 and nothing else.

Why is my int being passed through as 0?


Solution

  • Your problem is not surprisingly, in your call:

    I am calling the check_Mail like so: check_Mail("[email protected]", 30)

    Here you are passing in two arguments, but your function signature takes three arguments:

    def check_Mail(self, recipient="", loopfor=0)
    

    So what's happening is [email protected] is being assigned to self, and 30 to recipient:

        check_Mail("[email protected]", 30)
                    |        ----------^
                    V        V
    def check_Mail(self, recipient="", loopfor=0)
    

    If this method is not part of a class, remove the self argument from its definition. If it is part of a class, you need to pass a class instance, so either obj.check_Mail('[email protected]', 30) or checkMail(obj, '[email protected]', 30)