Skip to content

Instantly share code, notes, and snippets.

@AO8
Last active May 13, 2021 02:52
Show Gist options
  • Save AO8/d8b73d5a400f492d1c932641339006ff to your computer and use it in GitHub Desktop.
Save AO8/d8b73d5a400f492d1c932641339006ff to your computer and use it in GitHub Desktop.
Use a PIR sensor, Raspberry PI, and PiCamera to detect motion, take a timestamped photo, then attach it and send from Gmail with Python.
# Allow less secure apps to access your Gmail account
from gpiozero import MotionSensor
from picamera import PiCamera
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
import smtplib
import os
import email
import sys
import time
camera = PiCamera()
pir = MotionSensor(4)
camera.rotation = 180 # specific to my setup
while True:
pir.wait_for_motion()
filename = datetime.now().strftime("%m-%d-%Y_%H.%M.%S.jpg")
time.sleep(1) # unsure how critical this .sleep camera warm-up is, still testing
camera.capture(filename)
pir.wait_for_no_motion()
img_data = open(filename, "rb").read()
f_time = datetime.now().strftime("%A %B %d %Y @ %H:%M:%S")
msg = MIMEMultipart()
msg["Subject"] = f_time
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
text = MIMEText("WARNING! Motion Detected!")
msg.attach(text)
image = MIMEImage(img_data, name=os.path.basename(filename))
msg.attach(image)
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()
s.login('yourGmailLogin','yourPassword')
s.sendmail("[email protected]", "[email protected]", msg.as_string())
s.quit()
@Charan17
Copy link

I am able to capture the photo but the captured photo is not been sent to mail..can you help me out with this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment