Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame^] | 1 | # Copyright (C) 2001 Python Software Foundation |
| 2 | # Author: barry@zope.com (Barry Warsaw) |
| 3 | |
| 4 | """Module containing encoding functions for Image.Image and Text.Text. |
| 5 | """ |
| 6 | |
| 7 | import base64 |
| 8 | from quopri import encodestring as _encodestring |
| 9 | |
| 10 | |
| 11 | |
| 12 | # Helpers |
| 13 | def _qencode(s): |
| 14 | return _encodestring(s, quotetabs=1) |
| 15 | |
| 16 | def _bencode(s): |
| 17 | # We can't quite use base64.encodestring() since it tacks on a "courtesy |
| 18 | # newline". Blech! |
| 19 | if not s: |
| 20 | return s |
| 21 | hasnewline = (s[-1] == '\n') |
| 22 | value = base64.encodestring(s) |
| 23 | if not hasnewline and value[-1] == '\n': |
| 24 | return value[:-1] |
| 25 | return value |
| 26 | |
| 27 | |
| 28 | |
| 29 | def encode_base64(msg): |
| 30 | """Encode the message's payload in Base64. |
| 31 | |
| 32 | Also, add an appropriate Content-Transfer-Encoding: header. |
| 33 | """ |
| 34 | orig = msg.get_payload() |
| 35 | encdata = _bencode(orig) |
| 36 | msg.set_payload(encdata) |
| 37 | msg['Content-Transfer-Encoding'] = 'base64' |
| 38 | |
| 39 | |
| 40 | |
| 41 | def encode_quopri(msg): |
| 42 | """Encode the message's payload in Quoted-Printable. |
| 43 | |
| 44 | Also, add an appropriate Content-Transfer-Encoding: header. |
| 45 | """ |
| 46 | orig = msg.get_payload() |
| 47 | encdata = _qencode(orig) |
| 48 | msg.set_payload(encdata) |
| 49 | msg['Content-Transfer-Encoding'] = 'quoted-printable' |
| 50 | |
| 51 | |
| 52 | |
| 53 | def encode_7or8bit(msg): |
| 54 | """Set the Content-Transfer-Encoding: header to 7bit or 8bit.""" |
| 55 | orig = msg.get_payload() |
| 56 | # We play a trick to make this go fast. If encoding to ASCII succeeds, we |
| 57 | # know the data must be 7bit, otherwise treat it as 8bit. |
| 58 | try: |
| 59 | orig.encode('ascii') |
| 60 | except UnicodeError: |
| 61 | msg['Content-Transfer-Encoding'] = '8bit' |
| 62 | else: |
| 63 | msg['Content-Transfer-Encoding'] = '7bit' |
| 64 | |
| 65 | |
| 66 | |
| 67 | def encode_noop(msg): |
| 68 | """Do nothing.""" |