Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Con
(self, charset)
| 361 | self.set_charset(charset) |
| 362 | |
| 363 | def set_charset(self, charset): |
| 364 | """Set the charset of the payload to a given character set. |
| 365 | |
| 366 | charset can be a Charset instance, a string naming a character set, or |
| 367 | None. If it is a string it will be converted to a Charset instance. |
| 368 | If charset is None, the charset parameter will be removed from the |
| 369 | Content-Type field. Anything else will generate a TypeError. |
| 370 | |
| 371 | The message will be assumed to be of type text/* encoded with |
| 372 | charset.input_charset. It will be converted to charset.output_charset |
| 373 | and encoded properly, if needed, when generating the plain text |
| 374 | representation of the message. MIME headers (MIME-Version, |
| 375 | Content-Type, Content-Transfer-Encoding) will be added as needed. |
| 376 | """ |
| 377 | if charset is None: |
| 378 | self.del_param('charset') |
| 379 | self._charset = None |
| 380 | return |
| 381 | if not isinstance(charset, Charset): |
| 382 | charset = Charset(charset) |
| 383 | self._charset = charset |
| 384 | if 'MIME-Version' not in self: |
| 385 | self.add_header('MIME-Version', '1.0') |
| 386 | if 'Content-Type' not in self: |
| 387 | self.add_header('Content-Type', 'text/plain', |
| 388 | charset=charset.get_output_charset()) |
| 389 | else: |
| 390 | self.set_param('charset', charset.get_output_charset()) |
| 391 | if charset != charset.get_output_charset(): |
| 392 | self._payload = charset.body_encode(self._payload) |
| 393 | if 'Content-Transfer-Encoding' not in self: |
| 394 | cte = charset.get_body_encoding() |
| 395 | try: |
| 396 | cte(self) |
| 397 | except TypeError: |
| 398 | # This 'if' is for backward compatibility, it allows unicode |
| 399 | # through even though that won't work correctly if the |
| 400 | # message is serialized. |
| 401 | payload = self._payload |
| 402 | if payload: |
| 403 | try: |
| 404 | payload = payload.encode('ascii', 'surrogateescape') |
| 405 | except UnicodeError: |
| 406 | payload = payload.encode(charset.output_charset) |
| 407 | self._payload = charset.body_encode(payload) |
| 408 | self.add_header('Content-Transfer-Encoding', cte) |
| 409 | |
| 410 | def get_charset(self): |
| 411 | """Return the Charset instance associated with the message's payload. |