简体   繁体   中英

Cannot to sent email via Python

I trying to send email via python using gmail smtp, but receiving the error:

Code:

import smtplib

FROM = "mail1@gmail.com"
TO = "mail2@gmail.com"

message = "Hello"
# Send the mail

server = smtplib.SMTP('smtp.gmail.com', 465)
server.ehlo()
server.starttls()
server.login('mail1@gmail.com', 'password')
server.sendmail(FROM, TO, message)
server.quit()

Response:

server = smtplib.SMTP('smtp.gmail.com', 465)
  File "C:\Python37\lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python37\lib\smtplib.py", line 338, in connect
    (code, msg) = self.getreply()
  File "C:\Python37\lib\smtplib.py", line 394, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

According to example at python documentation https://docs.python.org/3/library/smtplib.html

your code is missing the “From: and To:” headers

import smtplib

def prompt(prompt):
    return input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print("Enter message, end with ^D (Unix) or ^Z (Windows):")

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while True:
    try:
        line = input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print("Message length is", len(msg))
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

run the above example, then modify to your code posted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM