Fetch Gmail Archieved messages

Rick Johnson rantingrickjohnson at gmail.com
Tue Mar 15 13:02:19 EDT 2016


On Tuesday, March 15, 2016 at 5:48:15 AM UTC-5, Arshpreet Singh wrote:

> def inbox_week():
>     import imaplib
>     EMAIL = 'myusername at gmail.com'

I admit that this is pedantic, but you should really use
ADDRESS instead of EMAIL. ADDRESS more correctly complements
PASSWORD. But in any event, you did do well by spelling them
as constants, which implicitly means: "Hey, don't mutate
these values!"

>     PASSWORD = 'mypassword'
>     mail = imaplib.IMAP4_SSL('imap.gmail.com')
>     mail.login(  EMAIL, PASSWORD )
>     mail = imaplib.IMAP4_SSL('imap.gmail.com')
>     mail.select("[Gmail]/All Mail")
>     interval = (date.today()-timedelta(d)).strftime("%d-%b-%Y")
>     _, data = mail.uid('search', None,'(SENTSINCE{date})'.format(date=interval))
>         
>     for num in data[0].split():
>         _, data = mail.uid('fetch', num, '(BODY.PEEK[])')
>     
>         for response_part in data:
>             if isinstance(response_part, tuple):
>                 msg = email.message_from_string(response_part[1])
>                 for header in ['to']:
>                
> # This is logic for inbox-archieved messages
>                     if (EMAIL in str(msg[header]) in str(msg[header])):

Is that last line doing what you think it's doing? Let's
break it down... Basically you have one condition, that is
composed of two main components:

    Component-1: EMAIL in str(msg[header])

and 

    Component-2: str(msg[header])
     

"Component-1" will return a Boolean. So in essence you're
asking:

    boolean = EMAIL in str(msg[header])
    if boolean in str(msg[header]):
        do_something()
     
Is that really what you wanted to do? I'm not sure how you
will ever find a Boolean in a string. Unless i've missed
something...? It will also help readability if you only 
applied str() to the value *ONCE*. But, maybe you don't 
even need the str() function???




More information about the Python-list mailing list