Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are binary file objects. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. The '
(input, output, quotetabs, header=False)
| 42 | |
| 43 | |
| 44 | def encode(input, output, quotetabs, header=False): |
| 45 | """Read 'input', apply quoted-printable encoding, and write to 'output'. |
| 46 | |
| 47 | 'input' and 'output' are binary file objects. The 'quotetabs' flag |
| 48 | indicates whether embedded tabs and spaces should be quoted. Note that |
| 49 | line-ending tabs and spaces are always encoded, as per RFC 1521. |
| 50 | The 'header' flag indicates whether we are encoding spaces as _ as per RFC |
| 51 | 1522.""" |
| 52 | |
| 53 | if b2a_qp is not None: |
| 54 | data = input.read() |
| 55 | odata = b2a_qp(data, quotetabs=quotetabs, header=header) |
| 56 | output.write(odata) |
| 57 | return |
| 58 | |
| 59 | def write(s, output=output, lineEnd=b'\n'): |
| 60 | # RFC 1521 requires that the line ending in a space or tab must have |
| 61 | # that trailing character encoded. |
| 62 | if s and s[-1:] in b' \t': |
| 63 | output.write(s[:-1] + quote(s[-1:]) + lineEnd) |
| 64 | elif s == b'.': |
| 65 | output.write(quote(s) + lineEnd) |
| 66 | else: |
| 67 | output.write(s + lineEnd) |
| 68 | |
| 69 | prevline = None |
| 70 | while 1: |
| 71 | line = input.readline() |
| 72 | if not line: |
| 73 | break |
| 74 | outline = [] |
| 75 | # Strip off any readline induced trailing newline |
| 76 | stripped = b'' |
| 77 | if line[-1:] == b'\n': |
| 78 | line = line[:-1] |
| 79 | stripped = b'\n' |
| 80 | # Calculate the un-length-limited encoded line |
| 81 | for c in line: |
| 82 | c = bytes((c,)) |
| 83 | if needsquoting(c, quotetabs, header): |
| 84 | c = quote(c) |
| 85 | if header and c == b' ': |
| 86 | outline.append(b'_') |
| 87 | else: |
| 88 | outline.append(c) |
| 89 | # First, write out the previous line |
| 90 | if prevline is not None: |
| 91 | write(prevline) |
| 92 | # Now see if we need any soft line breaks because of RFC-imposed |
| 93 | # length limitations. Then do the thisline->prevline dance. |
| 94 | thisline = EMPTYSTRING.join(outline) |
| 95 | while len(thisline) > MAXLINESIZE: |
| 96 | # Don't forget to include the soft line break `=' sign in the |
| 97 | # length calculation! |
| 98 | write(thisline[:MAXLINESIZE-1], lineEnd=b'=\n') |
| 99 | thisline = thisline[MAXLINESIZE-1:] |
| 100 | # Write out the current line |
| 101 | prevline = thisline |