简体   繁体   中英

How do I first login then continue to check gmail via imaplib and python

I have been working on a small Arduino project to activate a servo with a flag on it every time I get a new e-mail in GMail. I would like to log into Gmail, check to see if I have any new e-mail and then check again every x seconds.

What I have discovered is that the first connection goes fine, but after that, I get an error that I cannot use LOGIN when in AUTH mode, only NONAUTH . This suggests to be that once I have a logged in session, GMail won't take the method.

Here is the script:

import serial
import time
import imaplib, re
import getpass

user = raw_input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")
ser = serial.Serial('/dev/tty.usbmodemfa141', 9600)
print "Starting on " +ser.name;
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
while (True):
    conn.login(user,pwd)
    unreadCount = int(re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1))
    if(unreadCount > 0):
        print str(unreadCount) + " new mails!"
        ser.write("M")
    else:
        print "no mail :("
        ser.write("N")
    time.sleep(5)

My thoughts are that I use conn.login() once and then another command in a loop after that, OR I could logout after I check and then log back in each time.

Thoughts? Suggestions?

You need to take the "conn.login(user,pwd)" line out of the while loop. Putting it as the line before the while loop should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM