Search code examples
pythonpython-2.7encodingmailer

Encoding error with mailer module


When I use the mailer module (installed on Windows with pip) with python 2.7, I have an encoding error if I use non-ascii character.

For example, with the following snippet:

import mailer

message = mailer.Message()
message.From = "me@example.com"
message.To = "shan-x@server.com"
message.Subject = "Test"
message.Body = "Stuff with special characters like à or ç"

mailer = mailer.Mailer('my_relay-smtp')
mailer.send(message)

Then I receive the following email:

Stuff with special characters like ?? or ??

I've tried this:

message.Body = "Stuff with special characters like à or ç".decode('utf-8')

(Or with encode). But then I get an error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 35: ordinal not in range(128)

Solution

  • The answer is explicit in the help string for class Message:

    Use the charset property to send messages using other than us-ascii

    So you should use:

    message = mailer.Message(charset='utf8')
    message.From = "me@example.com"
    message.To = "shan-x@server.com"
    message.Subject = "Test"
    message.Body = "Stuff with special characters like à or ç".decode('utf-8')
    
    mailer = mailer.Mailer('my_relay-smtp')
    mailer.send(message)