将多封电子邮件写入文本文件 Python IMAP

Writing multiple Emails to a text file Python IMAP

我目前有一个在金字塔网络应用程序中运行的代码。通过按下一个按钮,网络应用程序运行一个功能,从收件箱中读取未读的电子邮件,删除前 6 行(不重要的信息)并将它们写入文件。稍后,此数据用作 matplotlib 的绘图数据。我目前的问题是代码一次只能读取一封未读的电子邮件。这意味着如果我有 5 封未读的电子邮件,其中包含我想写入文件的数据,则按下按钮只会写入一封电子邮件的数据,而我想要所有 5 封电子邮件的数据。

有什么方法可以一次读取所有未读邮件并将它们写入文本文件吗?我一直在考虑添加计算未读邮件数量的代码,它一直循环 read/write 函数,直到未读数量达到 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 的同一迭代中写作和阅读 ... 在相同的缩进级别。基本上在每次迭代中你是:

  • 收到电子邮件
  • 写入文件
  • 阅读该文件(此时似乎没用,只需使用正文)
  • 仍然"here",在读取文件后写入另一个文件并截断​​第一个文件。

更糟糕的是,return 也在 for 下...因此您将在第一次迭代时返回。
我认为你的代码应该更像

@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 latest_email_uid in data[0].split():
        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)
        with open('C:/Email/file.txt', 'a') as myfile:  # Opens file.txt and writes the email body
            for part in email_message.walk():
                if part.get_content_type() == 'text/plain':
                    body = part.get_payload(decode=True)
                    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)



    return Response('<h3>Data update successful</h3>'
        + '<form class="anchor" action="http://localhost:8888"><input class="homebutton" type="submit" value="Return" /></form>')

稍后编辑:我真的不知道在中间文件中写入的原因是什么,我认为您代码中的真正问题可能是 return 的 "wrong" 缩进