mail.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """Mail handling
  2. @copyright: 2022 Ansgar <ansgar@debian.org>
  3. @license: GNU General Public License version 2 or later
  4. """
  5. import daklib.gpg
  6. import email
  7. import email.message
  8. import email.policy
  9. from typing import cast
  10. def sign_mail(msg: email.message.EmailMessage, *, digest_algorithm: str = "SHA256", **kwargs) -> email.message.EmailMessage:
  11. """sign an email message using GnuPG.
  12. This only handles non-multipart messages.
  13. """
  14. mime_data = email.message.MIMEPart()
  15. mime_data.set_content(msg.get_payload())
  16. # Copy Content-Transfer-Encoding from unsigned message
  17. del mime_data["Content-Transfer-Encoding"]
  18. mime_data["Content-Transfer-Encoding"] = msg["Content-Transfer-Encoding"]
  19. data = mime_data.as_bytes(policy=email.policy.SMTP)
  20. sig = daklib.gpg.sign(data, **kwargs, digest_algorithm=digest_algorithm)
  21. mime_sig = email.message.MIMEPart()
  22. mime_sig['Content-Type'] = 'application/pgp-signature'
  23. mime_sig.set_payload(sig)
  24. msg.clear_content()
  25. del msg['Content-Type']
  26. msg['Content-Type'] = f'multipart/signed; micalg="pgp-{digest_algorithm.lower()}"; protocol="application/pgp-signature"'
  27. msg.set_payload([mime_data, mime_sig])
  28. return msg
  29. # TODO [python3.10, pep604]:
  30. # def parse_mail(msg: bytes | str) -> email.message.EmailMessage:
  31. def parse_mail(msg) -> email.message.EmailMessage:
  32. if isinstance(msg, str):
  33. # We need a cast as the return type depends on the `policy` argument.
  34. return cast(email.message.EmailMessage, email.message_from_string(msg, policy=email.policy.SMTPUTF8))
  35. else:
  36. # We need a cast as the return type depends on the `policy` argument.
  37. return cast(email.message.EmailMessage, email.message_from_bytes(msg, policy=email.policy.SMTPUTF8))