从emai的附件提取To:header

2024-06-06 20:31:13 发布

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

我用python在服务器上打开一封电子邮件(POP3)。每封电子邮件都有一个附件,附件本身就是转发的电子邮件。在

从“我需要得到的附件”地址。在

我用python来帮助我学习这门语言,但我还不是那么好!在

我的密码是这样的

import poplib, email, mimetypes

    oPop = poplib.POP3( 'xx.xxx.xx.xx' )
    oPop.user( 'abc@xxxxx.xxx' )
    oPop.pass_( 'xxxxxx' )

    (iNumMessages, iTotalSize ) = oPop.stat()

    for thisNum in range(1, iNumMessages + 1): 
          (server_msg, body, octets) = oPop.retr(thisNum)
          sMail = "\n".join( body )

          oMsg = email.message_from_string( sMail )

          # now what ?? 

我知道我有电子邮件作为电子邮件类的一个实例,但我不确定如何获取附件

我知道使用

^{pr2}$

从主邮件中获取“收件人:”标头,但如何从附件中获取?在

我试过了

for part in oMsg.walk():
    oAttach = part.get_payload(1)

但我不知道如何处理这个对象。我试着把它变成一根绳子然后把它传给

oMsgAttach = email.message_from_string( oAttach )

但那没用。我对python文档有点不知所措,需要一些帮助。提前谢谢。在


Tags: infor附件电子邮件emailbodyxxxxx
1条回答
网友
1楼 · 发布于 2024-06-06 20:31:13

如果我的收件箱里没有一封具有代表性的电子邮件,就很难把这封邮件处理完(我从未使用过poplib)。话虽如此,但从我的一点调查中可能会有所帮助:

首先,充分利用python的命令行接口和dir()和{}函数:这些函数可以告诉你很多关于即将出现的内容。您可以始终在代码中插入help(oAttach)dir(oAttach)和{},以了解它循环时发生了什么。如果您逐行在命令行界面中键入它,在这种情况下会更容易。在

我认为你需要做的是仔细检查每一个附件并找出它是什么。对于传统的电子邮件附件,它可能是base64编码的,所以这样做可能会有帮助:

#!/usr/bin/python
import poplib, email, mimetypes

# Do everything you've done in the first code block of your question
# ...
# ...

import base64
for part in oMsg.walk():
    # I've removed the '1' from the argument as I think you always get the
    # the first entry (in my test, it was the third iteration that did it).
    # However, I could be wrong...
    oAttach = part.get_payload()
    # Decode the base64 encoded attachment
    oContent = b64decode(oAttach)
    # then maybe...?
    oMsgAttach = email.message_from_string(oContent)

请注意,您可能需要在每种情况下检查oAttach,以检查它是否看起来像一条消息。得到sMail变量后,将其打印到屏幕上。然后,您可以在其中查找Content-Transfer-Encoding: base64之类的内容,这将为您提供一条关于附件是如何编码的线索。在

正如我所说,我没有使用任何poplib、email或mimetypes模块,所以我不确定这是否有用,但我认为这可能会为您指明正确的方向。在

相关问题 更多 >