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.com\r\nTo: YYYY@gmail.com\r\n\r\n{subject}\n\n{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:\Users\XXXX\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 253, in __init__
(code, msg) = self.connect(host, port)
File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 341, in connect
(code, msg) = self.getreply()
File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38\lib\smtplib.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!