0

I am using following code:

def mailme():
    print('connecting')
    server = smtplib.SMTP('mail.server.com', 26)
    server.connect("mail.server.com", 465)
    print('connected..')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('scraper@server.com', "pwd")
    text = 'TEST 123'
    server.sendmail('me@sserver.com', 'me@server2.com', text)
    server.quit()

but it gives error:

raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

When connect via Telnet it works:

~ telnet mail.zoo00ooz.com 26
Trying 1.2.3.4...
Connected to server.com.
Escape character is '^]'.
220-sh97.surpasshosting.com ESMTP Exim 4.87 #1 Mon, 01 Jan 2018 00:23:02 -0500 
220-We do not authorize the use of this system to transport unsolicited, 
220 and/or bulk e-mail.
^C^C
Volatil3
  • 14,253
  • 38
  • 134
  • 263

2 Answers2

3

I have attached the sample mailing code using Python 3.6.0 below

import smtplib as sl
server = sl.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login('sender_mail_id@gmail.com','sender_password')
server.sendmail('sender_mail_id@gmail.com',['first_receiver_mail_id@gmail.com','second_receiver_mail_id@gmail.com','and_so_on@gmail.com'],'data')
0

You don't need to connect twice ! As the documentation says:

exception smtplib.SMTPServerDisconnected¶

This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.

Your code should be more something like this (even like this its somewhat over complicated, see documentation for a sample code)

def mailme():
    SERVER_NAME='mail.whatever.com'
    SERVER_PORT=25
    USER_NAME='user'
    PASSWORD='password'
    print('connecting')
    server = smtplib.SMTP(SERVER_NAME, SERVER_PORT)
    print('connected..')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(USER_NAME, PASSWORD)
    text = 'TEST 123'
    server.sendmail('whoever@whatever.com', 'another@hatever.com', text)
    server.quit()

mailme()
MCO System
  • 404
  • 5
  • 12