dom_r
dom_r

Reputation: 1

Error smtplib in python

i've a python script, run on a raspeberry pi that monitoring my server room and periodically send me an e-mail and make other stuff. First time script is running it send a notification and works fine, then wait for a time (5 or 30 minutues) depending if an alarm is triggered, so i've write a for loop to wait. when the loop is finish, script make a call of the function for sending e-mail and python return an error. Could someone help me ? i test it also on debian 7.7.0 box and i've the same error. Below a sample script and the error. Thanks in advance. Dom.

File "/usr/lib/python2.7/smtplib.py", line 361, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

# Import
from time import sleep
import time
import smtplib
import sys
import string
smtp_server = "10.0.0.4" # mail server address
mail_from = "[email protected]" 
mail_to = "[email protected]" 
mail_subj = "Server room notify" 

server = smtplib.SMTP(smtp_server)
valore = 24 # value for the funtion

def SendAlertEmail(t_value):
    log_t = time.strftime("%d/%m/%A %H:%M:%S ")
    Text = string.join("Server room notify \n " + str(log_t) + str(t_value))
    Body_email = string.join((
       "From: %s" % mail_from,
       "To: %s" % mail_to,
       "Subject: %s" % mail_subj,
       "",
       Text
       ), "\r\n")
    server.sendmail(mail_from,mail_to,Body_email)
    return

SendAlertEmail(valore) # calling from here works fine
for i in range(0,500):
    sleep(1)
    print(str(i))

SendAlertEmail(valore) # after 500 secs goes in error. Test on debian 7.7.0 python 2.7.3 gcc 4.7.2

Upvotes: 0

Views: 1196

Answers (2)

user2317421
user2317421

Reputation:

As Serge Ballesta mentions, you should open and close the connection to the server for each one the sent e-mails.

Some months ago I programmed a class to send e-mails in Python, which you can find here: https://github.com/kmundnic/Habitus/blob/master/data_sender.py You create a DataSender object and it handles the connections to the server. Also, it calls a JSON file where the accounts and password is stored, so you don't save it in your code.

Feel free to use it. It was adapted from http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html, as it's mentioned in the comments at the beginning of the source code.

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148900

smtplib opens a TCP connection at the creation of the SMTP object. You try to reuse it after 500 seconds of inactivity when it is likely that a timeout has already closed the connection.

You should keep only the server name, an create a new SMTP object for each connection in your use case, because the delay between sending messages is too high.

Upvotes: 2

Related Questions