mailer modu编码错误

2024-03-29 02:35:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在python2.7中使用the mailer module(用pip安装在Windows上)时,如果使用非ascii字符,则会出现编码错误。你知道吗

例如,使用以下代码段:

导入邮件程序

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)

然后我收到以下电子邮件:

Stuff with special characters like ?? or ??

我试过这个:

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

(或使用encode)。但是我得到一个错误:

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

Tags: ortheincommessagemailer错误with
1条回答
网友
1楼 · 发布于 2024-03-29 02:35:05

答案在类消息的帮助字符串中是显式的:

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

所以你应该使用:

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)

相关问题 更多 >