Getting mail attachment to python file object

后端 未结 3 702
小鲜肉
小鲜肉 2020-12-02 10:10

I have got an email multipart message object, and I want to convert the attachment in that email message into python file object. Is this possible? If it is possible, what m

3条回答
  •  死守一世寂寞
    2020-12-02 10:50

    Actually using now-suggested email.EmailMessage API (don't confuse with old email.Message API) it is fairly easy to:

    1. Iterate over all message elements and select only attachments

    2. Iterate over just attachments

    Let's assume that you have your message stored as byte content in envelope variable

    Solution no.1:

    import email
    from email.message import EmailMessage
    
    email_message: EmailMessage = email.message_from_bytes(envelope, _class=EmailMessage)
    
    for email_message_part in email_message.walk():
        if email_message.is_attachment():
            # Do something with your attachment
    

    Solution no.2: (preferable since you don't have to walk through other parts of your message object)

    import email
    from email.message import EmailMessage
    
    email_message: EmailMessage = email.message_from_bytes(envelope, _class=EmailMessage)
    
    for email_message_attachment in email_message.iter_attachments():
            # Do something with your attachment
    

    Couple things to note:

    1. We explicitly tell to use new EmailMessage class in our byte read method through _class=EmailMessage parameter
    2. You can read your email message (aka envelope) from sources such as bytes-like object, binary file object or string thanks to built-in methods in message.Parser API

提交回复
热议问题