0

I am trying to send an email inside a while loop but if the sendmail fails, I want the script to log the error and continue:

while True:

input_state = GPIO.input(5)
if input_state == True:
    now = datetime.datetime.now().strftime("%m-%d-%y-%H%M%S")
    logging.debug('Motion detected at ' + now)
    name = 'tempimage.jpg'
    camera.capture(name)
    new_name = '/home/pi/image' + str(now) + '.jpg'
    os.rename(name, new_name)
    try:
        server = smtplib.SMTP( "smtp.gmail.com", 587 )
        server.starttls()
        server.login( '<login to gmail>', '<password>' )
        server.sendmail( 'Front Porch', '<myphone number>@vtext.com', 'Picture just taken on Front Porch' ) #Chuck
        server.close()
    else:
        logging.debug('Send of text failed ' + now)
    time.sleep(3)
else:
    now = datetime.datetime.now().strftime("%m-%d-%y-%H%M%S")
    logging.debug('No Motion ' + now)
    time.sleep(3)

When I execute this at boot it stalls at the try. I know this is a Duh moment in the making but really need it to work. Any help greatly appreciated.

3
  • 2
    You have a try with no except or finally. This isn't going to stall at the try; this is going to outright fail to compile. Commented Aug 29, 2017 at 23:44
  • 1
    Perhapse you meant except AppropriateExceptionType instead of else. Commented Aug 29, 2017 at 23:44
  • You guys are awesome! I knew this had to be a Duh moment. Many thanks, adding an Except capture as below fixed everything. Commented Aug 30, 2017 at 8:42

1 Answer 1

0
input_state = GPIO.input(5)
if input_state == True:
    now = datetime.datetime.now().strftime("%m-%d-%y-%H%M%S")
    logging.debug('Motion detected at ' + now)
    name = 'tempimage.jpg'
    camera.capture(name)
    new_name = '/home/pi/image' + str(now) + '.jpg'
    os.rename(name, new_name)
    try:
        server = smtplib.SMTP( "smtp.gmail.com", 587 )
        server.starttls()
        server.login( '<login to gmail>', '<password>' )
        server.sendmail( 'Front Porch', '<myphone number>@vtext.com', 'Picture just taken on Front Porch' ) #Chuck
        server.close()
    except Exception as e:
        logging.debug('Send of text failed ' + now + 'Exception '+e)
    time.sleep(3)
else:
    now = datetime.datetime.now().strftime("%m-%d-%y-%H%M%S")
    logging.debug('No Motion ' + now)
    time.sleep(3)

Try this code (I used except, not else and recorded the exception).

Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly! Many thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.