In this tutorial, we will look, how to capture video from raspberry pi when it detects motion (PIR sensor) and also send that video directly to email as an alert. So that you can instantly see who is in your room with the help of the video. I kept this set up near the window, as soon as birds comes in the range of PIR sensor, Camera starts recording them. So let’s get started.

Motion detection Video Captured Email Alert Using Raspberry Pi 4 bird

If you like this project you can also see motion detection email alert and motion detection photo captured email alert.

Components Required:
  1. Raspberry pi 4,
  2. Push Button,
  3. Pi Cam V2.1,
  4. PIR sensor (HC-SR501),
  5. 220 ohms Resistor,
  6. LED,
  7. Breadboard,
  8. Jumper Wire.
Enable Camera of Raspberry Pi:

Go to Menu-> Preferences -> Raspberry pi configuration -> interfaces -> Enable Camera

Raspberry pi configuration

Enable Camera for Raspberry pi 4

Create New Gmail Account (For sending Notification):

I suggest you to create new Gmail or Yahoo account for raspberry pi notification sender email. Because you will be giving less secure apps access to the account you send from. Make sure you give access to less secure apps, otherwise email won’t be sent.

Allow less secure apps for gmail

Allow less secure apps for gmail

Find SMTP Server Setting for Email Account:

Simple Mail Transfer Portocol (SMTP): For sending email through code, You will need a SMTP server setting. Each email provider has different SMTP server. Here I am using gmail account so, I am using gmail SMTP server setting, If you are not using gmail for sending notification, you have to use your email provider’s SMTP server setting.

You can see settings here for Gmail account and for Yahoo account.

Gmail SMTP Server Settings:

Gmail SMTP server address: smtp.gmail.com

Gmail SMTP Port TLS: 587

Gmail SMTP Port SSL: 465

Yahoo Mail SMTP Server Settings:

Yahoo Mail SMTP server address: smtp.mail.yahoo.com

Yahoo Mail SMTP port TLS: 587

Yahoo Mail SMTP port SSL: 465

If PIR sensor is not working:

It happens when you buy new sensor, It is not working. But it is not sensor fault, it is trim port which is in by default position. if you adjust sensor sensitivity and trigger time port. It will start to work as expected. Make sure knob of trigger time port is to the left side as low trigger time and sensitivity port at middle.

PIR sensor Trim port setting time trigger PIR sensor Trim port setting Sensitivity

Converting H264 Video to MP4 Format using Python Code:

When Pi cam record the video, it is in h264 format, which is not video player friendly. Even if some video player plays h264 video format but it will miss some frames or behaves weirdly. Due to this you will need to convert this from h264 format to MP4 format. As a result you can view your video in any video player. The same converted video will be sent to the email.

Install MP4Box:

For converting video from H264 to MP4 you will need MP4Box. For installing MP4Box. Open terminal and type,

sudo apt update

then

sudo apt install -y gpac
Circuit diagram for Raspberry Pi Motion Camera Detection:

 

Burglar detector with photo captured email alert notification circuit

PIR Sensor – GPIO20

LED – GPIO17

Push Button – GPIO16

Code for Raspberry Pi Motion Detection Camera Captured Video Email Alert:
from gpiozero import MotionSensor, Button, LED
from picamera import PiCamera
from email.mime.multipart import MIMEMultipart
from subprocess import call 
import os
import email.mime.application
import datetime
import smtplib
from time import sleep

pir = MotionSensor(20)
camera = PiCamera()
led = LED(17)
button = Button(16)

#replace the next three lines with your credentials
from_email_addr = 'Sender_Email_ID@gmail.com'
from_email_password = 'Password'
to_email_addr = 'Receiver_Email_ID@gmail.com'

#Create Alarm State by default it is off.
Alarm_state = False

while True:

    if button.is_pressed:
        Alarm_state = True
        print('Alarm ON')

    if Alarm_state == True:
        led.on()
        sleep(1)
        if pir.motion_detected:
            print("Motion Detected")
            led.off()
            #Video record
            camera.resolution = (640,480)
            camera.rotation = 180
            camera.start_recording('alert_video.h264')
            camera.wait_recording(50)
            camera.stop_recording()

            #coverting video from .h264 to .mp4
            command = "MP4Box -add alert_video.h264 alert_video.mp4"
            call([command], shell=True)
            print("video converted")


            #Create the Message
            msg = MIMEMultipart()
            msg[ 'Subject'] = 'INTRUDER ALERT..!!'
            msg['From'] = from_email_addr
            msg['To'] = to_email_addr


            # Video attachment
            Captured = '/home/pi/Desktop/alert_video.mp4'
            fp=open(Captured,'rb')
            att = email.mime.application.MIMEApplication(fp.read(),_subtype=".mp4")
            fp.close()
            att.add_header('Content-Disposition','attachment',filename='video' + datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S') + '.mp4')
            msg.attach(att)

            print("attach successful")

            #removing .h264 & .mp4 extra files
            os.remove("/home/pi/Desktop/alert_video.h264")

            #renaming file
            os.rename('alert_video.mp4', datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S') + '.mp4')

            #send Mail
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(from_email_addr, from_email_password)
            server.sendmail(from_email_addr, to_email_addr, msg.as_string())
            server.quit()
            print('Email sent')
            Alarm_state = False
Code Explanation:

Import required libraries.

from gpiozero import MotionSensor, Button, LED
from picamera import PiCamera
from email.mime.multipart import MIMEMultipart
from subprocess import call
import os
import email.mime.application
import datetime
import smtplib
from time import sleep

Creating an object that refer to PIR sensor, LED, PiCamera and button.

pir = MotionSensor(20)
camera = PiCamera()
led = LED(17)
button = Button(16)

Modify this with your sender email address and password. Enter email address where you want to receive email.

from_email_addr = 'Sender_Email_ID@gmail.com'
from_email_password = 'Sender_Password'
to_email_addr = 'Receiver_ID@gmail.com'

When program execute, alarm mode will be off by default.

Alarm_state = False

This will make script run in loop.

while True:
Alarm Mode:

For turning ON alarm mode, we need to push the button, if button pressed, it will make alarm true and print alarm ON.

if button.is_pressed:
Alarm_state = True
print('Alarm ON')

After pressing the button, LED will light up, shows the alarm mode is ON.

if Alarm_state == True:
led.on()
sleep(1)

LED will be off after motion detected and shows alarm mode is OFF.

if pir.motion_detected:
print("Motion Detected")
led.off()
Motion Detection Video Recording:
camera.resolution = (640,480)
camera.rotation = 180
camera.start_recording('alert_video.h264')
camera.wait_recording(2)
camera.stop_recording()

as soon as motion detected it will start recording, You can set camera resolution, camera rotation according to your need.

camera.resolution = (640,480)
camera.rotation = 180

Recorded file will be save as alert_video.h264 on desktop or location of your script file.

camera.start_recording('alert_video.h264')

Enter the number of seconds, it should record after motion detection. If you are giving high resolution I would suggest put less number of seconds. Because recorded file will exceed 25MB and Google will not allow to send more than 25MB file. 640X480, 60 second video of bird takes 17MB.

camera.wait_recording(50)
Converting .H264 to .MP4 using Python Code:
command = "MP4Box -add alert_video.h264 alert_video.mp4"
call([command], shell=True)
print("video converted")

Here we are using command to convert the file from .h264 to .mp4.

Create the Message:
msg = MIMEMultipart()
msg[ 'Subject'] = 'INTRUDER ALERT..!!'
msg['From'] = from_email_addr
msg['To'] = to_email_addr

You can change the subject line of email.

Video Attachment to the email by using Python:
Captured = '/home/pi/Desktop/alert_video.mp4'
fp=open(Captured,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype=".mp4")
fp.close()
att.add_header('Content-Disposition','attachment',filename='video' + datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S') + '.mp4')
msg.attach(att)

captured location is on desktop, if you are not saving your python script on desktop, you will need to change this location.

Removing & Renaming Recorded File:

Now we have two files one with .h264 & second with .mp4, so we are removing .h264 file.

os.remove("/home/pi/Desktop/alert_video.h264")

Second mp4 file with the name of alert_video.mp4 can be easily overwrite if you run this code again, so here we are changing the file name to current data and time.

os.rename('alert_video.mp4', datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S') + '.mp4')
Send the Email:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email_addr, from_email_password)
server.sendmail(from_email_addr, to_email_addr, msg.as_string())
server.quit()
print('Email sent')
Alarm_state = False

Finally send the email. Make sure you change your SMTP server address & port, If you are using google then no need to change any thing.

Video:

I hope you enjoyed this tutorial. For more content like this please subscribe to my YouTube Channel.