Python SMTP library can’t handle IPv6

How can i add IPv6 option on SMTP library please ?

When i try to connect to SMTP using IPv6 i got this error :

 smtpserver = smtplib.SMTP("smtp.gmail.com", 587, source_address=('2a00:xxxx:5::1e7', 80, 0, 0))

Error : TypeError: AF_INET address must be a pair (host, port)

Which means smtplib.py doesn’t support IPv6

I found an article about that “https://bugs.python.org/issue3461” . I tried to add the patch into my smtplib.py but it didn’t work

Can anyone please help me to do this ?

Answer

... source_address=('2a00:xxxx:5::1e7', 80, ...

The error message is misleading. Doing an strace on Linux shows that it actually tries to bind to the given IP and port but fails – and then issues this misleading error message. Why it fails can have various reason, but typical cases might be that it is no permission to bid to the port (binding to port 80 as done here needs root privileges) or that the port is already in use by another socket (port 80 is usually used for web servers).

In general it is better to only specify the IP address and leave the port to 0. This way it will use the given IP address as source IP but pick a random (ephemeral) port as source port.

I found an article about that “https://bugs.python.org/issue3461”

This is unrelated. It is only about the sender shown in the EHLO command during the SMTP dialog. If this is a problem just give the value to use with the local_hostname argument.