title: How do I first login then continue to check gmail via imaplib and python
body: <p>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.  </p>
  
  <p>What I have discovered is that the first connection goes fine, but after that, I get an error that I <strong>cannot use LOGIN when in AUTH mode, only NONAUTH</strong>.  This suggests to be that once I have a logged in session, GMail won't take the method.</p>
  
  <p>Here is the script:</p>
  
  <pre><code>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 &gt; 0):
          print str(unreadCount) + " new mails!"
          ser.write("M")
      else:
          print "no mail :("
          ser.write("N")
      time.sleep(5)
  </code></pre>
  
  <p>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.</p>
  
  <p>Thoughts? Suggestions?</p>