Sending email in utf-8?

Fredrik Lundh fredrik at pythonware.com
Mon Nov 7 12:24:50 EST 2005


"morphex" <morphex at gmail.com> wrote:

> I have an email that's in the utf-8 encoding, and I'm getting this
> error message when I try to send it using smtplib:
>
>    * Module smtplib, line 688, in sendmail
>    * Module smtplib, line 485, in data
>    * Module smtplib, line 312, in send
>    * Module socket, line 1, in sendall
>
> UnicodeEncodeError: 'ascii' codec can't encode characters in position
> 263-264: ordinal not in range(128)
>
> any suggestions on how I can approach this so that the email can be
> sent without raising errors?

looks like you're confusing Unicode (character set) and UTF-8 (encoding).

smtplib only deals with 8-bit character streams; if you want to use a specific
encoding, you have to apply it yourself *before* you call the library:

    HOST = "..."
    FROM = "..."
    TO = "..."
    BODY = u"..."

    server = smtplib.SMTP(HOST)
    server.sendmail(FROM, [TO], BODY.encode("utf-8"))
    server.quit()

</F> 






More information about the Python-list mailing list