UnicodeEncodeError:“ascii”编解码器无法对位置134处的字符“\xf6”进行编码:序号不在范围内(128)

2024-10-03 09:07:13 发布

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

我正在尝试创建一个python程序,其中包括发送电子邮件,我得到了UnicodeEncodeError错误。我看到的关于这个错误的解决方案在我的脚本中都不起作用。我试图在for循环中添加receiver = str(u' '.join(receiver).encode('utf-8')),但效果不好。这是我的一部分代码(如果你愿意,我可以发布全部代码):

werewolfs = []

def group_roles(group):
    for i in range(4):
        werewolfs.append(group[i])


group_roles(group1)
group_roles(group2)
group_roles(group3)

for receiver in werewolfs:
    receiver = str(u' '.join(receiver).encode('utf-8'))
    DATA = 'From:%s\nTo:%s\nSubject:%s\n\n%s' % (my_email, receiver, subject, werewolf_mail)
    server.sendmail(my_email, receiver, DATA)

这是整个错误消息:

Traceback (most recent call last):
  File "/home/dominikb/.config/JetBrains/PyCharmCE2020.3/scratches/werewolf.py", line 131, in <module>
    server.sendmail(my_email, receiver, DATA)
  File "/usr/lib/python3.9/smtplib.py", line 859, in sendmail
    msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 134: ordinal not in range(128)

有人知道这个问题的解决办法吗?那太好了。提前谢谢


Tags: infordataemailmy错误groupsendmail
2条回答

str()尝试使用默认字符编码器编码unicode字符(\xf6)的问题。要解决您的问题,您可以删除str(),只需使用.encode()

receiver = u' '.join(receiver).encode('utf-8')

我解决了我的问题!我发现它不起作用,因为我写的信息中有像ä、ö、ü和ß这样的德语字母。我把它们取下来,它就起作用了。还有没有办法用python编写包含此类信件的电子邮件

相关问题 更多 >