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