Q:

raspberry pi: no internet email and mysql connection

I have made a program on a raspberry pi that takes inputs from multiple sensors and sends that data out via emails and up to a remote mysql database.
The problem is that if the device loses internet for what ever reason it crashes the code. Is there a way to tell python that if it fails, try again in so many seconds and loop around until it gets reconnected?
Thanks

A:

"It crashes the code" isn't a very helpful description of what goes wrong (better to say that a particular piece of code produces a specific error message). So I am assuming that an smtplib.SMTP object's sendmail() method is raising an smtplib.SMTPException or some subclass thereof.
The trick is to catch the exception and retry, but you shouldn't really do this forever. You probably need something like
import smtplib
    ...
sender = smtplib.SMTP(...)
    ...
retry_count = 10
done = False
while not done:
    sender.sendmail(...)
    done = True
except smtplib.SMTPException:
    if retry_count:
        retry_count -= 1
    else:
        raise <some exception you can catch in surrounding code if necessary>

You may also want to put a time.sleep() call in where you decrement the retry count, as an immediate retry is unlikely to be successful.
If the exception is something more basic like a socket timeout error you may need to catch that instead.

