paul@1279 | 1 | #!/usr/bin/env python |
paul@1279 | 2 | |
paul@1279 | 3 | """ |
paul@1279 | 4 | Mail-related utilities. |
paul@1279 | 5 | |
paul@1279 | 6 | Copyright (C) 2015, 2016, 2017 Paul Boddie <paul@boddie.org.uk> |
paul@1279 | 7 | |
paul@1279 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@1279 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@1279 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@1279 | 11 | version. |
paul@1279 | 12 | |
paul@1279 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@1279 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@1279 | 15 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@1279 | 16 | details. |
paul@1279 | 17 | |
paul@1279 | 18 | You should have received a copy of the GNU General Public License along with |
paul@1279 | 19 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@1279 | 20 | """ |
paul@1279 | 21 | |
paul@1279 | 22 | from email.generator import Generator |
paul@1279 | 23 | |
paul@1279 | 24 | try: |
paul@1279 | 25 | from cStringIO import StringIO |
paul@1279 | 26 | except ImportError: |
paul@1279 | 27 | from StringIO import StringIO |
paul@1279 | 28 | |
paul@1279 | 29 | def message_as_string(message): |
paul@1279 | 30 | |
paul@1279 | 31 | """ |
paul@1279 | 32 | Return the string representation of 'message', attempting to preserve the |
paul@1279 | 33 | precise original formatting. |
paul@1279 | 34 | """ |
paul@1279 | 35 | |
paul@1279 | 36 | out = StringIO() |
paul@1279 | 37 | generator = Generator(out, False, 0) # disable reformatting measures |
paul@1279 | 38 | generator.flatten(message) |
paul@1279 | 39 | return out.getvalue() |
paul@1279 | 40 | |
paul@1279 | 41 | def decode_part(part): |
paul@1279 | 42 | |
paul@1279 | 43 | """ |
paul@1279 | 44 | Change the transfer encoding on 'part' and its subparts so that a plain text |
paul@1279 | 45 | representation may be displayed. |
paul@1279 | 46 | """ |
paul@1279 | 47 | |
paul@1279 | 48 | payload = part.get_payload(decode=True) |
paul@1279 | 49 | if payload: |
paul@1279 | 50 | encoding = part.get("Content-Transfer-Encoding") |
paul@1279 | 51 | if encoding: |
paul@1279 | 52 | del part["Content-Transfer-Encoding"] |
paul@1279 | 53 | part["Content-Transfer-Encoding"] = "8bit" |
paul@1279 | 54 | part.set_payload(payload) |
paul@1279 | 55 | else: |
paul@1279 | 56 | for p in part.get_payload(): |
paul@1279 | 57 | decode_part(p) |
paul@1279 | 58 | |
paul@1279 | 59 | # vim: tabstop=4 expandtab shiftwidth=4 |