pythonsmtpgmail

Connection Error SMTP python: smtplib.SMTPServerDisconnected: please run connect() first


I've been using python for a bit now and have been using the email function without any errors in the past but on the latest program I have made I've been getting this error

 Traceback (most recent call last):
    File "daemon.py", line 62, in <module>
    scraper.run()
    File "c:\cfsresd\scraper.py", line 48, in run
    self.scrape()
    File "c:\cfsresd\scraper.py", line 44, in scrape
    handler(msg)
    File "daemon.py", line 57, in handler
    server.ehlo()
    File "C:\Python27\lib\smtplib.py", line 385, in ehlo
    self.putcmd(self.ehlo_msg, name or self.local_hostname)
    File "C:\Python27\lib\smtplib.py", line 318, in putcmd
    self.send(str) 
    File "C:\Python27\lib\smtplib.py", line 310, in send
    raise SMTPServerDisconnected('please run connect() first')
    smtplib.SMTPServerDisconnected: please run connect() first

I used the same email code for all my projects but this is first time is done it. I've tried adding the connect() but that made no difference. Below is email section of my script

msg = MIMEText ('%s - %s' % (msg.text, msg.channel))
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    msg['Subject'] = "msg.channel"
    msg['From'] = ('removed')
    msg['To'] = ('removed')
    server.login('user','password')
    server.sendmail(msg.get('From'),msg["To"],msg.as_string())
    server.close()
    server.ehlo()
    server.quit()
    print('sent')

Solution

  • All sorted took a few idea and tried the code below:

    msg = MIMEText ('%s - %s' % (msg.text, msg.channel))
    server = smtplib.SMTP('smtp.gmail.com')
    server.starttls()
    server.login('user','pass')
    msg['Subject'] = "msg.channel"
    msg['From'] = ('from')
    msg['To'] = ('to')
    server.sendmail(msg.get('From'),msg["To"],msg.as_string())
    server.quit()
    

    So I removed ehlo(), close() and port number. Now I have to workout how to change the subject to msg.channel so it changes each time.