In this example, the event is when an object is moving.
#Import
from gpiozero import DistanceSensor
from gpiozero import LED
from gpiozero import Buzzer
import smtplib
from time import sleep
#Email Variables
SMTP_SERVER = ‘smtpXXXX’ #Email Server
SMTP_PORT = 587 #Server Port
MAIL_USERNAME = ‘USERNAME’ #change this to match your account
MAIL_PASSWORD = ‘PASSWORD’ #change this to match your password
class Emailer:
def sendmail(self, recipient, subject, content):
#Create Headers
headers = [“From: ” + MAIL_USERNAME, “Subject: ” + subject, “To: ” + recipient,
“MIME-Version: 1.0”, “Content-Type: text/html”]
headers = “\r\n”.join(headers)
#Connect to mail Server
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo()
#Login to Gmail
session.login(MAIL_USERNAME, MAIL_PASSWORD)
#Send Email & Exit
session.sendmail(MAIL_USERNAME, recipient, headers + “\r\n\r\n” + content)
session.quit
green_led = LED(21)
green_led.off()
bz = Buzzer(13)
bz.off()
sensor = DistanceSensor(echo=14, trigger=4)
while True:
di=int(sensor.distance * 100)
print(‘Distance: ‘, int(sensor.distance * 100), ‘ cm’)
if di > 10:
green_led.on()
bz.on()
print(“ALARM”)
sender = Emailer()
sendTo = ‘sendToEmailAddress’
emailSubject = “ALARM!”
emailContent = “The object is moving!”
#Sends an email to the “sendTo” address with the specified “emailSubject” as the subject and “emailContent” as the email content.
sender.sendmail(sendTo, emailSubject, emailContent)
if di < 10:
green_led.off()
bz.off()
sleep(1)