pythonemailgmailgmail-apismtplib

Why is my Python SMTPLib email script not working and how do I fix it?


So I used a Youtube Tutorial to write a basic Python email script. The comments said that the video was very helpful, yet my code is not working.

My code looks like this

from email.message import EmailMessage
import ssl
import smtplib

email_sender = 'correctemail@gmail.com'
email_password = "corr ectp assw ords"

email_receiver = 'throwaway@email.com'

subject = 'Written by Code!'
body = """
    This was written by my program! Tell me if it worked.
"""

em = EmailMessage()
em['From'] = email_sender
em['To'] = email_receiver
em['Subject']
em.set_content(body)

context = ssl.create_default_context()

with smtplib.SMTP_SSL('smtp.gmail.com', 465, context) as smtp:
    smtp.login(email_sender, email_password)
    smtp.sendmail(email_sender, email_receiver, em.as_string())

The Error looks like this: smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Does anybody know why it failed and how I can fix it? Thanks!


Solution

  • So I fixed my problem. I had to switch smtplib.SMTP_SSL('smtp.gmail.com', 465, context) for just smtplib.SMTP_SSL('smtp.gmail.com')

    I don't know why it worked