smtplib.Smtpserverdisconnected: Connection unexpectedly closed

Asked

Viewed 22 times

0

I was trying to send an email with python:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

host = 'smtp.gmail.com'
port = 587
user = '***********@gmail.com'
password = '*********'

print('Criando objeto servidor...')
server = smtplib.SMTP(host, port)

print('Login...')
server.ehlo()
server.starttls()
server.login(user, password)

message = 'Ola Mundo!'

print('Criando mensagem...')
email_msg = MIMEMultipart()
email_msg['From'] = user
email_msg['To'] = '*****************@gmail.com'
email_msg['Subject'] = 'Assunto da Mensagem'

print('Adicionando texto...')
email_msg.attach(MIMEText(message, 'plain'))

print('Enviando mensagem...')
server.sendmail(email_msg['From'], email_msg['To'], email_msg.as_string())

print('Mensagem enviada!')
server.quit()

Prompt:

Criando objeto servidor...
Login...
Criando mensagem...
Adicionando texto...
Enviando mensagem...
Traceback (most recent call last):
  File "c:\Users\Ivone\Desktop\git\web scraping\emailTest.py", line 29, in <module>
    server.sendmail(email_msg['From'], email_msg['To'], email_msg.as_string())
  File "C:\Users\Ivone\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 887, in sendmail
    (code, resp) = self.data(msg)
  File "C:\Users\Ivone\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 574, in data
    (code, msg) = self.getreply()
  File "C:\Users\Ivone\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 398, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
  • Did you allow third-party access to gmail? By default, gmail blocks scripted access. To send the email using python, you need to authorize access through non-standard ports first. Check this link: https://support.google.com/accounts/answer/6010255?hl=en

  • Is already activated

1 answer

-4

I found the answer: disable the antivirus email module (Avast, in my case)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.