This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author dmaurer
Recipients barry, dmaurer, r.david.murray
Date 2020-07-15.20:40:58
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
The following fixes the example:
from copy import copy
from io import BytesIO
from email.message import Message
from email.generator import BytesGenerator, _has_surrogates
from email._policybase import Compat32

class FixedBytesGenerator(BytesGenerator):
    def _handle_text(self, msg):
        payload = msg._payload
        if payload is None:
        charset = msg.get_param("charset")
        if charset is not None \
               and not self.policy.cte_type=='7bit' \
               and not _has_surrogates(payload):
            msg = copy(msg)
            msg._payload = payload.encode(charset).decode(
                "ascii", "surrogateescape")
    _writeBody = _handle_text

class FixedMessage(Message):
    def as_bytes(self, unixfrom=False, policy=None):
        policy = self.policy if policy is None else policy
        fp = BytesIO()
        g = FixedBytesGenerator(fp, mangle_from_=False, policy=policy)
        g.flatten(self, unixfrom=unixfrom)
        return fp.getvalue()

fixed_policy = Compat32(message_factory=FixedMessage)

ms = message_from_string(mt, policy=fixed_policy)
Date User Action Args
2020-07-15 20:40:58dmaurersetrecipients: + dmaurer, barry, r.david.murray
2020-07-15 20:40:58dmaurersetmessageid: <>
2020-07-15 20:40:58dmaurerlinkissue41307 messages
2020-07-15 20:40:58dmaurercreate