我正在尝试使用imap获取一个通过我的gmail收件箱查看的python脚本,并打印出任何看不见的电子邮件的主题和发件人。我已经开始了,但目前我认为它不能从这些主题和发件人中排序看不见的电子邮件或提取。< / p>
有谁知道如何完成此代码?
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
答案 0 :(得分:0)
如果你愿意使用poplib,这应该可行。
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.")
请务必在此处使用Google帐户中不太安全的应用:https://myaccount.google.com/lesssecureapps
答案 1 :(得分:0)
我的外部库 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'
注意:mailbox.fetch 有 mark_seen 参数!