简体   繁体   English

我如何先登录然后继续通过imaplib和python检查gmail

[英]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. 每当我在GMail中收到新电子邮件时,我就一直在研究一个小型Arduino项目,以激活带有标记的伺服器。 I would like to log into Gmail, check to see if I have any new e-mail and then check again every x seconds. 我想登录Gmail,检查是否有新电子邮件,然后每隔x秒检查一次。

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 . 我发现,第一个连接运行良好,但是之后,出现一个错误, 处于AUTH模式时,只能使用NONAUTH,不能使用LOGIN This suggests to be that once I have a logged in session, GMail won't take the method. 这表明一旦登录会话,GMail就不会采用该方法。

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. 我的想法是,我先使用conn.login(),然后再在循环中使用另一个命令,或者我可以在检查后注销,然后每次重新登录。

Thoughts? 有什么想法吗? Suggestions? 有什么建议吗?

You need to take the "conn.login(user,pwd)" line out of the while loop. 您需要从while循环中删除“ conn.login(user,pwd)”行。 Putting it as the line before the while loop should work fine. 将其放在while循环之前的行应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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