Sending email via Gmail SMTP error: smtplib.SMTPServerDisconnected: please run connect() first

Viewed 214

have been stuck on this for a few hours. Trying to send email from Python via Gmail SMTP

Gmail settings:

2 Step-Verification: Yes

App password created: Yes

Publishing status: Testing

User type: External

Code:

import smtplib
import ssl

port = 465  # For SSL
password = "example"

context = ssl.create_default_context()

with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
    server.login("test@gmail.com", password)

sender_email = "test@gmail.com"
receiver_email = "test@gmail.com"
message = """\
Subject: Test

Test."""

server.sendmail(sender_email, receiver_email, message)

This is the error message I'm getting:

Traceback (most recent call last):
  File "C:\Users\coopejo\PycharmProjects\pythonProject1\trawler\gmaillogin.py", line 20, in <module>
    server.sendmail(sender_email, receiver_email, message)
  File "C:\Users\coopejo\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 876, in sendmail
    (code, resp) = self.mail(from_addr, esmtp_opts)
  File "C:\Users\coopejo\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 540, in mail
    self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
  File "C:\Users\coopejo\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 373, in putcmd
    self.send(str)
  File "C:\Users\coopejo\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 365, in send
    raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first

Any help would be greatly appreciated.Thanks!

1 Answers

So the error raised is asking you to run connect() first, so it looks like you aren't connecting to the server before trying to send the email.

I would put the server.sendemail() line directly under the server.login() line, with the same indent. That way, the already-connected server object is used for both. That's how it works in my code.

However, you're in bad luck here. As of May 30th, Google no longer allows insecure third-party apps to send emails this way. I'm looking into using a more secure auth method now and I'll update you if I find a working method.

Related