title: PGP-signing multipart e-mails with Python
body: <p>I'm currently trying to add PGP signing support to <a href="https://launchpad.net/~mitya57/+junk/mailsender" rel="noreferrer">my small e-mail sending script</a> (which uses Python 3.x and <a href="http://code.google.com/p/python-gnupg/" rel="noreferrer">python-gnupg</a> module).</p>
  
  <p>The code that signs message is:</p>
  
  <pre><code>gpg = gnupg.GPG()
  basetext = basemsg.as_string().replace('\n', '\r\n')
  signature = str(gpg.sign(basetext, detach=True))
  if signature:
      signmsg = messageFromSignature(signature)
      msg = MIMEMultipart(_subtype="signed", micalg="pgp-sha1",
      protocol="application/pgp-signature")
      msg.attach(basemsg)
      msg.attach(signmsg)
  else:
      print('Warning: failed to sign the message!')
  </code></pre>
  
  <p>(Here <code>basemsg</code> is of <a href="http://docs.python.org/py3k/library/email.message.html" rel="noreferrer"><code>email.message.Message</code></a> type.)</p>
  
  <p>And <code>messageFromSignature</code> function is:</p>
  
  <pre><code>def messageFromSignature(signature):
      message = Message()
      message['Content-Type'] = 'application/pgp-signature; name="signature.asc"'
      message['Content-Description'] = 'OpenPGP digital signature'
      message.set_payload(signature)
      return message
  </code></pre>
  
  <p>Then I add all the needed headers to the message (<code>msg</code>) and send it.</p>
  
  <p>This works well for non-multipart messages, but fails when <code>basemsg</code> is multipart (<code>multipart/alternative</code> or <code>multipart/mixed</code>).</p>
  
  <p>Manually verifying the signature against the corresponding piece of text works, but Evolution and Mutt report that the signature is bad.</p>
  
  <p>Can anybody please point me to my mistake?</p>