Problems with email.Generator.Generator

Manlio Perillo manlio_perilloNO at SPAMlibero.it
Mon Sep 11 12:44:31 EDT 2006


Chris Withers ha scritto:
> [...]
> 
> OK, but I fail to see how replacing one unicode error with another is
> any help... :-S
> 


The problem is simple: email package does not support well Unicode strings.

For now I'm using this:

charset = "utf-8" # the charset to be used for email


class HeadersMixin(object):
    """A custom mixin, for automatic internationalized headers
    support.
    """

    def __setitem__(self, name, val, **_params):
        if isinstance(val, str):
            try:
                # only 7 bit ascii
                val.decode("us-ascii")
            except UnicodeDecodeError:
                raise ValueError("8 bit strings not accepted")

            return self.add_header(name, val)
        else:
            try:
                # to avoid unnecessary trash
                val = val.encode('us-ascii')
            except:
                val = Header.Header(val, charset).encode()

                return self.add_header(name, val)


class MIMEText(HeadersMixin, _MIMEText.MIMEText):
    """A MIME Text message that allows only Unicode strings, or plain
    ascii (7 bit) ones.
    """

    def __init__(self, _text, _subtype="plain"):
        _charset = charset

        if isinstance(_text, str):
            try:
                # only 7 bit ascii
                _text.decode("us-ascii")
                _charset = "us-ascii"
            except UnicodeDecodeError:
                raise ValueError("8 bit strings not accepted")
        else:
            _text = _text.encode(charset)

        return _MIMEText.MIMEText.__init__(self, _text, _subtype, _charset)


class MIMEMultipart(HeadersMixin, _MIMEMultipart.MIMEMultipart):
        def __init__(self):
            _MIMEMultipart.MIMEMultipart.__init__(self)



This only accepts Unicode strings or plain ascii strings.




Regards  Manlio Perillo



More information about the Python-list mailing list