我有一些代码可以从我的Gmail帐户中读取最旧的电子邮件,但我希望它能够阅读每封电子邮件。我是python的新手,上周我开始学习它。我对c ++有很多经验,所以我知道循环是什么,我只需要帮助在python中实现它。
我的代码所做的是读取最旧的电子邮件,然后创建一个int来保存主题中的数字,然后从1到10获取一个随机数,并打印电子邮件中主题中的数字是否等于随机数号。
我希望程序循环播放并为收件箱中的每封电子邮件执行此操作。
import poplib
import string, random
import StringIO, rfc822
import logging
import random
SERVER = "pop.gmail.com"
USER = "XXXXXXXXXXXXXX"
PASSWORD = "XXXXXXXXXXXX"
# connect to server
logging.debug('connecting to ' + SERVER)
server = poplib.POP3_SSL(SERVER)
#server = poplib.POP3(SERVER)
# login
logging.debug('logging in')
server.user(USER)
server.pass_(PASSWORD)
# list items on server
logging.debug('listing emails')
resp, items, octets = server.list()
# download the first message in the list
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(FROM_EMAIL,FROM_PWD)
mail.select('inbox')
type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])
for i in range(latest_email_id, first_email_id, -1):
id, size = string.split(items[0])
resp, text, octets = server.retr(id)
# convert list to Message object
text = string.join(text, "\n")
file = StringIO.StringIO(text)
message = rfc822.Message(file)
# output message
print(message['From']),
print(message['Subject']),
print(message['Date']),
#print(message.fp.read())
mynumber = message['Subject']
myint = int(mynumber)
print "Let's play a game! I'll choose a number between 0 and 10. Try to guess it!"
python_number = random.randint(0,10)
if python_number == myint:
print "You won! My number was " + str(python_number)
else:
print "You loose! My number was " + str(python_number)
答案 0 :(得分:1)
你想要做的不是获得第一项
id, size = string.split(items[0])
你想得到所有物品:
for item in items:
id, size = string.split(item)
然后在此后缩进代码,以便为item
中的每个items
运行
import poplib
import string, random
import StringIO, rfc822
import logging
import random
SERVER = "pop.gmail.com"
USER = "myEmail"
PASSWORD = "myPassword"
# connect to server
logging.debug('connecting to ' + SERVER)
server = poplib.POP3_SSL(SERVER)
# login
logging.debug('logging in')
server.user(USER)
server.pass_(PASSWORD)
# list items on server
logging.debug('listing emails')
resp, items, octets = server.list()
for item in items:
#For each message
id, size = string.split(item)
resp, text, octets = server.retr(id)
# convert list to Message object
text = string.join(text, "\n")
file = StringIO.StringIO(text)
message = rfc822.Message(file)
# output message
print(message['From']),
print(message['Subject']),
print(message['Date']),
#print(message.fp.read())
mynumber = message['Subject']
myint = int(mynumber)
print "Let's play a game! I'll choose a number between 0 and 10. Try to guess it!"
python_number = random.randint(0,10)
if python_number == myint:
print "You won! My number was " + str(python_number)
else:
print "You loose! My number was " + str(python_number)