获得电子邮件主题的简单方法是什么

时间:2018-10-15 21:12:24

标签: python

以下内容可能不太好,但是它对我有用,并将电子邮件文本保存到文本文件中。我希望文本文件具有包含在电子邮件主题中的名称,该名称看起来像是“学生编号,星期编号”。

因此,我想将file ='email'+ str(msgNum)+'.txt'更改为file = email_subject

如何将其集成到此循环中?

for msgNum in unseenMessages:
        file = 'email' + str(msgNum) + '.txt'
        theFile = open(pathToFiles + file, 'w')
        rawMessage = server.fetch(unseenMessages, ['BODY[]', 'FLAGS'])
        message = pyzmail.PyzMessage.factory(rawMessage[msgNum][b'BODY[]'])
        text = message.text_part.get_payload().decode(message.text_part.charset)
        #textCut = text.split()
        #saveText = ''.join(textCut)
        saveText = text.rstrip()
        theFile.write(saveText)
        theFile.close()
        server.set_flags(msgNum, '\Seen', silent=False) # Mark them as seen
        print('Email UID ' + str(msgNum) + 'saved and marked SEEN')

我可以使用'from imapclient import IMAPClient'这样的主题:

messages = server.search('UNSEEN')
    for uid, message_data in server.fetch(messages, 'RFC822').items():
        email_message = email.message_from_bytes(message_data[b'RFC822'])
        print(uid, email_message.get('From'), email_message.get('Subject'))

但是我不知道如何将其集成到我的循环中。

我尝试过:

message = server.fetch([178], 'RFC822').items()

这使我相信整个消息。主题在那里,但我看不到如何提取

1 个答案:

答案 0 :(得分:0)

电子邮件只是对多项选择问题的解答。保存后我整理文本,然后与答案键进行比较。这是一个示例文本:

  

1825010301,A,B,A,A,A,C,H,G,A,C,F,D,G,D,E,G,H,H,C,A,A,B,A ,A,C,B,C,D,A,E,J,G,H,F,I

     

发自我的iPhone

我又捏造了一种解决方案,虽然不是很优雅,但是我发现这可行。如果可以改善,我会很高兴,我不是编码员!!这只是将文本保存到我的笔记本电脑,然后我可以休闲地对其进行分析。

for uid, message_data in server.fetch(unseenMessages, 'RFC822').items():
        email_message = email.message_from_bytes(message_data[b'RFC822'])
        print(email_message.get('Subject'))
        messageSubject = email_message.get('Subject')
        file = messageSubject + '.txt'
        theFile = open(pathToFiles + file, 'w')
        rawMessage = server.fetch(unseenMessages, ['BODY[]', 'FLAGS'])
        message = pyzmail.PyzMessage.factory(rawMessage[uid][b'BODY[]'])
        text = message.text_part.get_payload().decode(message.text_part.charset)
        saveText = text.rstrip()
        theFile.write(saveText)
        theFile.close()
        #server.set_flags(msgNum, '\Seen', silent=False) # Mark them as seen
        print('Email UID ' + str(uid) + 'saved and marked SEEN')