我目前有一个在金字塔网络应用程序中工作的代码。通过按下一个按钮,这个web应用程序运行一个功能,从收件箱中读取未读的电子邮件,删除前6行(不重要的信息)并将它们写入一个文件。稍后,该数据将用作matplotlib的打印数据。我目前的问题是,代码一次只能读取一封未读的电子邮件。这意味着,例如,如果我有5封未读的电子邮件,其中包含我要写入文件的数据,则按下按钮只会写入一封电子邮件的数据,而我需要所有5封电子邮件的数据。你知道吗
有没有一种方法可以一次读取所有未读的电子邮件并将其写入文本文件?我一直在考虑添加计算未读邮件数量的代码,它不断循环读/写功能,直到未读数量达到0。也许有更专业的方法来做这件事,所以我问。提前谢谢!你知道吗
这是我目前的代码:
@view_config(route_name='update-data')
def update_view(request):
m = imaplib.IMAP4_SSL('imap.gmail.com')
m.login('email@gmail.com', 'password')
m.list()
m.select('inbox')
result, data = m.uid('search', None, 'FROM', '"senderEmail"', 'UNSEEN') # Only unseen mail
i = len(data[0].split()) #space separate string
if i == 0:
return Response('<head><link rel="stylesheet" href="/static/styleplot.css"/></head>'
+ '<h3> Data cannot be updated </h3><h4>No new emails</h4>'
+ '<form class="anchor" action="http://localhost:8888"><input class="homebutton" type="submit" value="Return" /></form>')
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = m.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = email_data[0][1]
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
with open('C:/Email/file.txt', 'a') as myfile: # Opens file.txt and writes the email body
myfile.write(str(body))
with open('C:/Email/file.txt', 'r+') as f: # Opens file.txt again in read mode and reads lines
lines = f.readlines()
with open ('C:/Email/newfile.txt','a') as g: # Writes file.txt contents to newfile.txt, starting from line 6, deletes contents of the first file
g.writelines(lines[6:])
f.truncate(0)
else:
continue
return Response('<h3>Data update successful</h3>'
+ '<form class="anchor" action="http://localhost:8888"><input class="homebutton" type="submit" value="Return" /></form>')
可能是因为您在
for
的同一个迭代中编写和阅读。。。在相同的缩进级别。基本上,每次迭代都是:为了让事情变得更糟,你有
return
也在for
下。。。因此您将在第一次迭代中返回。我觉得你的代码应该更像
稍后编辑:我真的不知道在中间文件中编写的原因是什么,我认为代码中真正的问题可能是
return
的“错误”缩进相关问题 更多 >
编程相关推荐