Skip to content

Instantly share code, notes, and snippets.

@Brutt
Created January 29, 2017 20:16
Show Gist options
  • Save Brutt/d84bee7940d256136e359765f2c2f3cf to your computer and use it in GitHub Desktop.
Save Brutt/d84bee7940d256136e359765f2c2f3cf to your computer and use it in GitHub Desktop.
Detection movement and sending email via gmail
import picamera
import time
import RPi.GPIO as GPIO
from datetime import datetime
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
#send e-mail via gmail
def send_mail(send_from, password, send_to, send_to_hidden, subject, file_name):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Subject'] = subject
with open(file_name, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(file_name)
)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(file_name)
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(send_from, password)
smtp.sendmail(send_from, [send_to] + [send_to_hidden], msg.as_string())
smtp.quit()
### main block ###
#number of GPIO on board
sensor = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN)
delay_sec = 60
mark_time = time.time()
cur_state = 0
while True:
time.sleep(1)
cur_state = GPIO.input(sensor)
print(cur_state)
if cur_state == 1:
if time.time() - mark_time > delay_sec:
delay_sec = 10
msg = "Some movement. Time: {0}".format(str(datetime.now())[:-7])
print(msg)
mark_time = time.time()
with picamera.PiCamera() as camera:
#photo
camera.resolution = (1280, 720)
time.sleep(1)
filename = '/home/pi/Desktop/Pictures/%s.jpg' % str(datetime.now())
camera.capture(filename)
#send email
send_mail('my_email@gmail.com',
'mypass',
'first_email@gmail.com',
'second_email@gmail.com',
str(datetime.now()),
filename)
#video
# filename = '/home/pi/Desktop/Pictures/%s.h264' % str(datetime.now())
# camera.start_recording(filename)
# time.sleep(5)
# camera.stop_recording()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment