Check unread count of Gmail messages with Python

后端 未结 7 1429
面向向阳花
面向向阳花 2020-12-22 17:41

How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.

7条回答
  •  甜味超标
    2020-12-22 18:18

    Well, I'm going to go ahead and spell out an imaplib solution as Cletus suggested. I don't see why people feel the need to use gmail.py or Atom for this. This kind of thing is what IMAP was designed for. Gmail.py is particularly egregious as it actually parses Gmail's HTML. That may be necessary for some things, but not to get a message count!

    import imaplib, re
    conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    conn.login(username, password)
    unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
    

    Pre-compiling the regex may improve performance slightly.

提交回复
热议问题