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

2024-04-25 18:56:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 数据代码formtxtuiddatastringraw
1条回答
网友
1楼 · 发布于 2024-04-25 18:56:00

可能是因为您在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的“错误”缩进

相关问题 更多 >