(string, charset, cte, policy)
| 142 | |
| 143 | |
| 144 | def _encode_text(string, charset, cte, policy): |
| 145 | lines = string.encode(charset).splitlines() |
| 146 | linesep = policy.linesep.encode('ascii') |
| 147 | def embedded_body(lines): return linesep.join(lines) + linesep |
| 148 | def normal_body(lines): return b'\n'.join(lines) + b'\n' |
| 149 | if cte is None: |
| 150 | # Use heuristics to decide on the "best" encoding. |
| 151 | if max((len(x) for x in lines), default=0) <= policy.max_line_length: |
| 152 | try: |
| 153 | return '7bit', normal_body(lines).decode('ascii') |
| 154 | except UnicodeDecodeError: |
| 155 | pass |
| 156 | if policy.cte_type == '8bit': |
| 157 | return '8bit', normal_body(lines).decode('ascii', 'surrogateescape') |
| 158 | sniff = embedded_body(lines[:10]) |
| 159 | sniff_qp = quoprimime.body_encode(sniff.decode('latin-1'), |
| 160 | policy.max_line_length) |
| 161 | sniff_base64 = binascii.b2a_base64(sniff) |
| 162 | # This is a little unfair to qp; it includes lineseps, base64 doesn't. |
| 163 | if len(sniff_qp) > len(sniff_base64): |
| 164 | cte = 'base64' |
| 165 | else: |
| 166 | cte = 'quoted-printable' |
| 167 | if len(lines) <= 10: |
| 168 | return cte, sniff_qp |
| 169 | if cte == '7bit': |
| 170 | data = normal_body(lines).decode('ascii') |
| 171 | elif cte == '8bit': |
| 172 | data = normal_body(lines).decode('ascii', 'surrogateescape') |
| 173 | elif cte == 'quoted-printable': |
| 174 | data = quoprimime.body_encode(normal_body(lines).decode('latin-1'), |
| 175 | policy.max_line_length) |
| 176 | elif cte == 'base64': |
| 177 | data = _encode_base64(embedded_body(lines), policy.max_line_length) |
| 178 | else: |
| 179 | raise ValueError("Unknown content transfer encoding {}".format(cte)) |
| 180 | return cte, data |
| 181 | |
| 182 | |
| 183 | def set_text_content(msg, string, subtype="plain", charset='utf-8', cte=None, |
no test coverage detected