Detecting if an email is a “Delivery Status Notification” and extract information - Python

后端 未结 3 1913
不思量自难忘°
不思量自难忘° 2021-02-13 18:35

I\'m using the Python email module to parse emails.

I need to be able to tell if an email is a \"Delivery Status Notification\", find out what the status is

3条回答
  •  灰色年华
    2021-02-13 18:43

    The docs you cited says that the message is multi-part if it is DSN:

    import email
    
    msg = email.message_from_string(emailstr)
    
    if (msg.is_multipart() and len(msg.get_payload()) > 1 and 
        msg.get_payload(1).get_content_type() == 'message/delivery-status'):
        # email is DSN
        print(msg.get_payload(0).get_payload()) # human-readable section
    
        for dsn in msg.get_payload(1).get_payload():
            print('action: %s' % dsn['action']) # e.g., "failed", "delivered"
    
        if len(msg.get_payload()) > 2:
            print(msg.get_payload(2)) # original message
    

    Format of a Delivery Status Notification (from rfc 3464):

    A DSN is a MIME message with a top-level content-type of
    multipart/report (defined in [REPORT]).  When a multipart/report
    content is used to transmit a DSN:
    
    (a) The report-type parameter of the multipart/report content is
        "delivery-status".
    
    (b) The first component of the multipart/report contains a human-
        readable explanation of the DSN, as described in [REPORT].
    
    (c) The second component of the multipart/report is of content-type
        message/delivery-status, described in section 2.1 of this
        document.
    
    (d) If the original message or a portion of the message is to be
        returned to the sender, it appears as the third component of the
        multipart/report.
    

提交回复
热议问题