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

时间:2018-08-02 12:20:50

标签: python web-applications imap

我目前有一个可在金字塔Web应用程序中使用的代码。通过按下按钮,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>')

1 个答案:

答案 0 :(得分:1)

可能是因为您正在for ...的同一迭代中以相同的缩进级别进行写入和读取。基本上,每次迭代都是:

  • 获取电子邮件
  • 写入文件
  • 读取该文件(此时仅使用正文似乎没用)
  • 仍然“在这里”,在读取文件后,您将写入另一个文件并截断​​第一个文件。

最糟糕的是,您在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

的“错误”缩进