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