Question

I'm trying to get a python script which looks through my gmail inbox using imap and prints out the subject and sender of any emails which are unseen. I've started but at the moment I don't think it can sort the unseen emails or extract from these the subject and sender.

Does anyone know how to finish this code?

import imaplib
import email
user = "x"
password = "y"

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user, password)
mail.list()
mail.select('inbox')

unseen_emails = mail.search(None, 'UnSeen')
print unseen_emails

No correct solution

OTHER TIPS

If you were willing to use poplib, this should work.

import poplib

mymail = []

host = "pop.gmail.com"
mail = poplib.POP3_SSL(host)
print (mail.getwelcome())
print (mail.user("user@gmail.com"))
print (mail.pass_("password"))
print (mail.stat())
print (mail.list())
print ("")

if mail.stat()[1] > 0:
    print ("You have new mail.")
else:
    print ("No new mail.")

print ("")

numMessages = len(mail.list()[1])
numb=0
for i in range(numMessages):
    for j in mail.retr(i+1)[1]:
        numb+=1
        if numb == 4 or numb == 5:
            print(j)

mail.quit()
input("Press any key to continue.")

Just be sure to allow less secure apps in your google account here: https://myaccount.google.com/lesssecureapps

My external lib https://github.com/ikvk/imap_tools

from imap_tools import MailBox, AND

# get list of unseen emails from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'pwd', 'INBOX') as mailbox:
    for msg in mailbox.fetch(AND(seen=False)):
        msg.subject   # str: 'some subject 你 привет'
        msg.from_     # str: 'Sender@ya.ru'

NOTE: mailbox.fetch has mark_seen arg!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top