socket.gaierror: [Errno 11001] getaddrinfo failed when sending gmail email via Python

Question:

I’m on Windows and using Python 3.9.10 and I have trouble sending an email via google smtp.

My code is :

import smtplib
from email.mime.text import MIMEText

def send_email(host, port, subject, msg, sender, recipients, password):
    msg = MIMEText(msg)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = ', '.join(recipients)
    smtp_server = smtplib.SMTP_SSL(host, port)
    smtp_server.login(sender, password)
    smtp_server.sendmail(sender, recipients, msg.as_string())
    smtp_server.quit()


def main():
    host = "smtp.gmail.com"
    port = 465

    user = <my email>
    pwd = <google app password>

    subject = "Test email"
    msg = "Hello world"
    sender = user
    recipients = [user]
    send_email(host, port, subject, msg, sender, recipients, pwd)


if __name__ == '__main__':
    main()

What I don’t understand is I keep getting the error socket.gaierror: [Errno 11001] getaddrinfo failed:

Traceback (most recent call last):
  File "%project_location%send_email_google.py", line 37, in <module>
    main()
  File "%project_location%send_email_google.py", line 33, in main
    send_email(host, port, subject, msg, sender, recipients, pwd)
  File "%project_location%send_email_google.py", line 13, in send_email
    smtp_server = smtplib.SMTP_SSL(host, port)
  File "%Python%libsmtplib.py", line 1050, in __init__
    SMTP.__init__(self, host, port, local_hostname, timeout,
  File "%Python%libsmtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "%Python%libsmtplib.py", line 341, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "%Python%libsmtplib.py", line 1056, in _get_socket
    new_socket = super()._get_socket(host, port, timeout)
  File "%Python%libsmtplib.py", line 312, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "%Python%libsocket.py", line 823, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "%Python%libsocket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

Process finished with exit code 1

I’m not using a VPN, proxies or anything.

I have checked, I have the correct host and the correct port for Gmail. I’m using the google app password thing. I just don’t get why it won’t work.

Thanks!

Asked By: gee3107

||

Answers:

I fixed it

I had a typo and my host was not "smtp.gmail.com" but was "'smtp.gmail.com'"

Answered By: gee3107
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.