Skip to content
Advertisement

Sending email with smtplib library with Python

Sending email with smtplib library with the below Python program, however, I get a SMTPServerDisconnected: Connection unexpectedly closed error.

import smtplib

subject = 'This is a test subject'
body = 'This is a test body'
message = ("From: XXXX@gmail.comrnTo: YYYY@gmail.comrnrn{subject}nn{body}")

server = smtplib.SMTP(host='smtp.gmail.com', port=465)

try:
    server.ehlo()
    server.starttls()
    server.login('XXXX@gmail.com', 'XXXX')
    server.sendmail('XXXX@gmail.com', 'YYYY.smithson@gmail.com', message)

except Exception as e:
    print(e)

finally:
    server.quit()

Full error code below:

Traceback (most recent call last):
  File "C:/Users/XXXX/PycharmProjects/New/Project/test.py", line 9, in <module>
    server = smtplib.SMTP(host='smtp.gmail.com', port=465)
  File "C:UsersXXXXAppDataLocalProgramsPythonPython38libsmtplib.py", line 253, in __init__
    (code, msg) = self.connect(host, port)
  File "C:UsersXXXXAppDataLocalProgramsPythonPython38libsmtplib.py", line 341, in connect
    (code, msg) = self.getreply()
  File "C:UsersXXXXAppDataLocalProgramsPythonPython38libsmtplib.py", line 398, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

When trying out port 587 for Google SMTP servers I get an authentication error, so I imagine 465 is the correct TLS port. I have also seen another post about adding the ‘From’ and ‘To’ headers and therefore added in my own adaptation. I have also enabled POP3 and IMAP in both Gmail accounts.

Appreciate your help in advance, recently started Python!

Advertisement

Answer

This is a different way to send emails with Python in SMTPLIB.

import smtplib
content = "-" # Enter your content here
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
main.login('EMAIL@something.com', 'PASSWORD TO YOUR ACCOUNT')
header = 'To:' + 'TO EMAIL' + 'n' + 'From:' 
         + 'FROM EMAIL' + 'n' + 'Subject: Sent email from python n'
content = header + content
mail.sendmail('FROM EMAIL', 'TO EMAIL', content) # (1) = Sender, (2) = Receiver
mail.close

Be careful to not fake you sent the email from an account you don’t own, if you do, it might cause some unwanted effects. Make sure that the emails you are typing in is valid and your own. Also, you might want to create a send email google account to send your mail to other people, because you will need to loosen security on that new email. First, create that gmail account and go to your circle avatar. Go to manage account > security > and toggle less secure apps to on. Don’t use this email for everything, only use it to send emails through python, because it’s safer.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement