来自https://docs.python.org/3/library/smtplib.html
你可以知道connect()需要一个字符串参数host。
一个 SMTP 实例封装了一个 SMTP 连接。它的方法支持完整的 SMTP 和 ESMTP 操作。如果给定了可选的主机和端口参数,则在初始化期间使用这些参数调用 SMTP connect() 方法。
connect()可以点击然后重定向到一个链接,然后你可以看到:
SMTP.connect(host='localhost', port=0)
连接到给定端口上的主机。默认设置是通过标准 SMTP 端口 (25) 连接到本地主机。如果主机名以冒号 (':') 后跟一个数字结尾,则该后缀将被删除,并且该数字被解释为要使用的端口号。如果在实例化期间指定了主机,则构造函数会自动调用此方法。返回服务器在其连接响应中发送的响应代码和消息的 2 元组。
在那里你可以知道参数host='localhost' 默认是一个字符串。
编辑
我检查了你的代码,
print(type(mxrecords))
打印
<class 'dns.name.Name'>
这表明mxrecords 对象是dns.name.Name 对象,而不是字符串。
如果你点击connect方法的源码,你会发现host应该是一个字符串:
def connect(self, host='localhost', port=0, source_address=None):
"""Connect to a host on a given port.
If the hostname ends with a colon (`:') followed by a number, and
there is no port specified, that suffix will be stripped off and the
number interpreted as the port number to use.
Note: This method is automatically invoked by __init__, if a host is
specified during instantiation.
"""
if source_address:
self.source_address = source_address
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i + 1:]
try:
port = int(port)
except ValueError:
raise OSError("nonnumeric port")
if not port:
port = self.default_port
if self.debuglevel > 0:
self._print_debug('connect:', (host, port))
self.sock = self._get_socket(host, port, self.timeout)
self.file = None
(code, msg) = self.getreply()
if self.debuglevel > 0:
self._print_debug('connect:', repr(msg))
return (code, msg)
您可以在代码中找到与您的错误相符的host.find(':') == host.rfind(':')。
查看dns.name.Name源代码,你会发现Name类有一个to_text方法:
def to_text(self, omit_final_dot=False):
"""Convert name to text format.
@param omit_final_dot: If True, don't emit the final dot (denoting the
root label) for absolute names. The default is False.
@rtype: string
"""
if len(self.labels) == 0:
return maybe_decode(b'@')
if len(self.labels) == 1 and self.labels[0] == b'':
return maybe_decode(b'.')
if omit_final_dot and self.is_absolute():
l = self.labels[:-1]
else:
l = self.labels
s = b'.'.join(map(_escapify, l))
return maybe_decode(s)
所以您应该使用mxrecords.to_text() 来获取 MX 服务器名称。