UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xc4 in position 0: invalid continuation byte

文章讲述了作者在编写自动推送邮件脚本时遇到UnicodeDecodeError,原因在于使用中文作为主机名。通过分析源码和错误信息,发现是gethostbyaddr函数在处理中文主机名时出错,解决方案是确保主机名使用正确的字符编码。
摘要由CSDN通过智能技术生成

目录

前言

错误分析


前言

编写一个自动推送邮件的脚本,在执行的时候一直报错提示“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
  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值