开发者

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

开发者 https://www.devze.com 2023-04-05 04:29 出处:网络
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 t

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 se开发者_运维问答rial
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号