title: Detecting if an email is a "Delivery Status Notification" and extract information - Python
body: <p>I'm using the Python <code>email</code> module to parse emails.</p>
  
  <p>I need to be able to tell if an email is a "Delivery Status Notification", find out what the status is, and extract information on the email that failed, eg. the Subject.</p>
  
  <p>The object I get after parsing with .parsestr(email) is like this:</p>
  
  <pre><code>{'Content-Transfer-Encoding': 'quoted-printable',
   'Content-Type': 'text/plain; charset=ISO-8859-1',
   'Date': 'Mon, 14 Mar 2011 11:26:24 +0000',
   'Delivered-To': 'sender@gmail.com',
   'From': 'Mail Delivery Subsystem &lt;mailer-daemon@googlemail.com&gt;',
   'MIME-Version': '1.0',
   'Message-ID': '&lt;000e08jf90sd9f00e6f943f@google.com&gt;',
   'Received': 'by 10.142.13.8 with SMTP id 8cs63078wfm;\r\n        Mon, 14 Mar 2011 04:26:24 -0700 (PDT)',
   'Return-Path': '&lt;&gt;',
   'Subject': 'Delivery Status Notification (Failure)',
   'To': 'sender@gmail.com',
   'X-Failed-Recipients': 'recipient@gmail.com'}
  </code></pre>
  
  <p><strong>Firstly</strong>, how do I tell that this is a DSN without using a regexp on the subject?</p>
  
  <p><strong>Secondly</strong>, <strike>how do I access the body of the email</strike>, and information such as the error that was returned by the mail server?</p>
  
  <p><strong>edit:</strong> worked out I need to use <code>.get_payload()</code> to get the contents of the message.</p>
  
  <p>The <a href="http://docs.python.org/library/email#differences-from-mimelib" rel="noreferrer">email docs</a> say:</p>
  
  <blockquote>
    <p><em>The Parser class has no differences in its public interface. <strong>It does
    have some additional smarts to
    recognize message/delivery-status type
    messages</strong>, which it represents as a
    Message instance containing separate
    Message subparts for each header block
    in the delivery status notification</em></p>
  </blockquote>
  
  <hr>
  
  <h2>Update:</h2>
  
  <p>Basically, I need to be able to reliable detect that an email is a DSN, and then also to extract the original message so I can parse that with email.Parser() and get information about it.</p>