【发布时间】:2019-03-22 05:02:04
【问题描述】:
我正在使用 .csv 文件创建一个伪数据库。基本上我要做的是当我启动我的代码时,我打开 .csv 文件并将所有值读入数组tempDB,然后进入我的无限循环以例行检查具有特定主题的新电子邮件是否有进来。在循环的每次迭代中,我打开一个 .csv 编写器。然后我连接到我的 gmail,并搜索与主题匹配的未读电子邮件。日期时间被解析,这是用于检查电子邮件是否已被此脚本读取过的内容。我遍历数组,检查新的日期时间字符串是否与 .csv 文件(包含在 tempDB 中)中的任何内容匹配。如果日期时间字符串与 tempDB 数组中的任何内容都不匹配,那么我将执行某个操作。我之所以以这种方式跟踪电子邮件,而不是通过此脚本将电子邮件设置为read,是因为我有另一个程序以较慢的间隔与相同的电子邮件交互。如果此代码已看到电子邮件,我希望它能够忽略电子邮件,但让我的其他应用程序将电子邮件标记为已读。以下是我的代码:
import imaplib, time, email, mailbox, datetime, csv
server = "imap.gmail.com"
port = 993
user = "Redacted"
password = "Redacted"
def main():
tempDB = []
infile = open('MsgDB.csv' 'r')
reader = csv.reader(infile)
for row in reader:
if any(row):
tempDB.append(row)
infile.close()
while True:
found = False
outfile = open('MsgDB.csv', 'w', newline='')
writer = csv.writer(outfile)
conn = imaplib.IMAP4_SSL(server, port)
conn.login(user, password)
conn.select('inbox', readonly=True)
result, data = conn.search(None, '(UNSEEN SUBJECT "Test Subject")')
i = len(data[0].split())
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = conn.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)
date_tuple = email.utils.parsedate_tz(email_message['Date'])
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
local_message_date = "%s" %(str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
for i in range(len(tempDB)):
if tempDB[i] == local_message_date:
print("Item Found")
found = True
continue
else:
print("Writing to file...")
tempDB.append(local_message_date)
writer.writerow([local_message_date])
for part in email_message.walk():
if part.get_content_type() == "text/plain" and found != True:
#DO THE THING
else:
continue
outfile.close()
time.sleep(30)
if __name__ == "__main__":
main()
据我所知,核心问题是永远不会写入 csv 文件,永远不会附加 tempDB。您会注意到,我已经为Item Found 和Writing to file... 放置了调试打印语句。但是,这些都没有打印,这告诉我循环很可能被完全跳过。但是,我确实打印了Local Message Date 和TempDB,它们始终打印与主题匹配的最新消息,并且 TempDB 始终为空。此外,在#DO THE THING 中发生的操作确实会发生。问题是,它将继续使用相同的电子邮件,即使它应该被写入该脚本已经读取的 .csv 文件。我在这里做错了什么?提前谢谢!
【问题讨论】:
-
"将所有值读入数组 tempDB":删除
if any(row):
标签: python python-3.x csv imaplib