Index: smtplib.py =================================================================== --- smtplib.py (revision 65264) +++ smtplib.py (working copy) @@ -235,27 +235,11 @@ self.timeout = timeout self.esmtp_features = {} self.default_port = SMTP_PORT + self.local_hostname = local_hostname if host: (code, msg) = self.connect(host, port) if code != 220: raise SMTPConnectError(code, msg) - if local_hostname is not None: - self.local_hostname = local_hostname - else: - # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and - # if that can't be calculated, that we should use a domain literal - # instead (essentially an encoded IP address like [A.B.C.D]). - fqdn = socket.getfqdn() - if '.' in fqdn: - self.local_hostname = fqdn - else: - # We can't find an fqdn hostname, so use a domain literal - addr = '127.0.0.1' - try: - addr = socket.gethostbyname(socket.gethostname()) - except socket.gaierror: - pass - self.local_hostname = '[%s]' % addr def set_debuglevel(self, debuglevel): """Set the debug output level. @@ -277,7 +261,8 @@ 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. + number interpreted as the port number to use. When using an IPv6 literal + address, the port must be passed as a seperate parameter. Note: This method is automatically invoked by __init__, if a host is specified during instantiation. @@ -295,6 +280,26 @@ self.sock = self._get_socket(host, port, self.timeout) (code, msg) = self.getreply() if self.debuglevel > 0: print>>stderr, "connect:", msg + + if self.local_hostname is None: + # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and + # if that can't be calculated, that we should use a domain literal + # instead (essentially an encoded IP address like [A.B.C.D]) or + # [IPv6:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]. + try: + name = socket.getnameinfo(self.sock.getsockname(), 0) + if self.sock.family == socket.AF_INET: + self.local_hostname = '[%s]' % name[0] + elif self.sock_family == socket.AF_INET6: + self.local_hostname = '[IPv6:%s]' % name[0] + else: + if self.debuglevel > 0: print>>stderr, "Unknown address family in SMTP socket" + except socket.gaierror, e: + if self.debuglevel > 0: print>>stderr, "Error while resolving hostname: ", e.string() + pass + else: + + return (code, msg) def send(self, str):