目录
前言
编写一个自动推送邮件的脚本,在执行的时候一直报错提示“UnicodeDecodeError”,我理解的是读取文件解码错误,因为在源码中我调用了配置文件和为邮件添加了附件,导致在错误的道路上走了一下午。
错误分析
部分源码如下:
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
# server.starttls() # 启动TLS加密
server.login(sender_email, password) # 登录邮箱账户
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text)
server.quit()
print("Email sent successfully!")
执行后报错如下:
Traceback (most recent call last):
File "e:\Microsoft VS Code\New Project for python\demo 1\.vscode\newProject\sendMail.py", line 40, in <module>
send_mail(subject1, recv_email1, msg1)
File "e:\Microsoft VS Code\New Project for python\demo 1\.vscode\newProject\sendMail.py", line 27, in send_mail
server = smtplib.SMTP_SSL(mail_host)
File "C:\Program Files\Python39\lib\smtplib.py", line 1045, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout,
File "C:\Program Files\Python39\lib\smtplib.py", line 265, in __init__
fqdn = socket.getfqdn()
File "C:\Program Files\Python39\lib\socket.py", line 791, in getfqdn
hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte
突然我打开文件了"C:\Program Files\Python39\lib\socket.py"文件,看到了这段代码的解释(从name中获取完全限定域名。空参数被解释为表示本地主机。首先检查gethostbyaddr()返回的主机名,然后可能是现有的别名。如果没有可用的FQDN,则使用主机名从gethostname()返回。)。
意思是gethostbyaddr(name)会获取到主机名,之前为了装逼把主机名修改成了狂炫酷炸吊爆天,所以是中文的,可能gethostbyaddr(name)会在计算机名为中文的时候报错UnicodeDecodeError
hostname, aliases, ipaddrs = gethostbyaddr(name)
def getfqdn(name=''):
"""Get fully qualified domain name from name.
An empty argument is interpreted as meaning the local host.
First the hostname returned by gethostbyaddr() is checked, then
possibly existing aliases. In case no FQDN is available, hostname
from gethostname() is returned.
"""
name = name.strip()
if not name or name == '0.0.0.0':
name = gethostname()
try:
hostname, aliases, ipaddrs = gethostbyaddr(name)
except error:
pass
else:
aliases.insert(0, hostname)
for name in aliases:
if '.' in name:
break
else:
name = hostname
return name