Motion Detection Video Captured Email Alert using Raspberry Pi 4

In this tutorial, we will explore how to capture video using a Raspberry Pi when motion is detected by a PIR sensor. Additionally, we will learn how to send the recorded video as an email alert, allowing you to instantly view who or what is in your room through the captured footage. For this setup, the Raspberry Pi, along with the camera module and PIR sensor, can be placed near a window. When birds or other subjects enter the PIR sensor's range, the camera will begin recording them. Let's proceed and delve into the tutorial.

If you find this project interesting, you may also want to explore other related projects such as motion detection email alerts and motion detection photo capture with email alerts. These projects provide additional functionalities and expand upon the concept of motion detection using the Raspberry Pi.

Components Required:

To complete this project, you will need the following components:

  • Raspberry Pi 4
  • Push Button
  • Pi Camera V2.1
  • PIR sensor (HC-SR501)
  • 220-ohm Resistor
  • LED
  • Breadboard
  • Jumper Wires

These components are essential for building the setup and implementing the functionality of motion detection with the Raspberry Pi..

Enable Camera of Raspberry Pi:

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

Create New Gmail Account (For sending Notification):

It is advisable to create a new Gmail or Yahoo account specifically for the purpose of sending notifications from the Raspberry Pi. This is because you will need to grant access to “less secure apps” in order for the email to be sent successfully. By using a separate account, you can ensure the security of your primary email account while allowing the Raspberry Pi to send notifications without any issues. Remember to adjust the account settings to allow access for less secure apps to enable the email functionality.

Find SMTP Server Setting for Email Account:

To send emails through code, you will require the SMTP (Simple Mail Transfer Protocol) server settings. Each email provider has its own SMTP server settings. In this case, I am using a Gmail account, so I will provide the Gmail SMTP server settings. If you are using a different email provider, you will need to use the corresponding SMTP server settings.

Here are the SMTP server settings for Gmail and Yahoo accounts:

Gmail SMTP Server Settings:

  • SMTP server address: smtp.gmail.com
  • SMTP Port for TLS: 587
  • SMTP Port for SSL: 465

Yahoo Mail SMTP Server Settings:

  • SMTP server address: smtp.mail.yahoo.com
  • SMTP Port for TLS: 587
  • SMTP Port for SSL: 465

If you encounter issues with the PIR sensor not working, it is often due to the trim pot (trimming potentiometer) being in the default position. Adjusting the sensor sensitivity and trigger time ports can help resolve this. Ensure that the knob of the trigger time port is positioned to the left for low trigger time, and the sensitivity port is set to the middle position.

By following these instructions, you should be able to configure the SMTP server settings for your specific email provider and resolve any issues with the PIR sensor.

Converting H264 Video to MP4 Format using Python Code:

When the Pi Camera records a video, it saves it in the H.264 format, which may not be compatible with all video players. Some video players may struggle to play H.264 videos, skipping frames or exhibiting unusual behavior. To address this, you will need to convert the video from the H.264 format to the more widely supported MP4 format. By converting the video to MP4, you can ensure compatibility with any video player. The converted video can then be sent via email, allowing for easy viewing by the recipient.

Install MP4Box:

To install MP4Box for converting videos from H.264 to MP4 format, follow these steps:

  1. Open the terminal on your Raspberry Pi.
  2. Type the following command:
sudo apt update
  1. Press Enter to execute the command.

This command will install the necessary package, which includes MP4Box. Once the installation is complete, you can use MP4Box to convert your H.264 videos to the MP4 format.

Circuit diagram for Raspberry Pi Motion Camera Detection:

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 = '[email protected]'
from_email_password = 'Password'
to_email_addr = '[email protected]'

#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)

To modify the code with your sender email address, password, and recipient email address, follow these steps:

  1. Locate the section of the code where the sender's email address and password are specified.
  2. Replace the existing sender's email address with your own email address in the appropriate field.
  3. Replace the existing password with your own email account password.
  4. Locate the section of the code where the recipient's email address is specified.
  5. Replace the existing recipient's email address with the desired email address where you want to receive the email.

By making these modifications, the code will be customized to use your own email credentials and send the email alerts to the specified recipient email address.

from_email_addr = '[email protected]'
from_email_password = 'Sender_Password'
to_email_addr = '[email protected]'

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')

Please specify the desired duration for recording after motion detection in seconds. If you are using a high resolution for recording, it is recommended to keep the duration relatively shorter. This is because higher resolution videos can result in larger file sizes, and it's important to consider the file size limit for sending emails. For instance, Google typically has a file size limit of 25MB. As an example, a 640×480 resolution video of 60 seconds capturing a bird may result in a file size of around 17MB.

To ensure successful email transmission, it's advised to adjust the recording duration accordingly and consider the resolution of the video being captured.

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)

By default, the captured location for the files is set to the desktop. If you have saved your Python script in a different location, you will need to modify the file path accordingly.

To remove and rename the recorded files, follow these steps:

  1. Locate the section of the code where the captured location is specified.
  2. If you need to change the location, modify the file path to the desired location. For example, if you want to save the files in a folder named “captures” located on the desktop, you can use the following path: /home/pi/Desktop/captures/.
  3. To remove the .h264 file, you can add the following code after converting the video to MP4 format:

This code uses the os.remove() function to delete the .h264 file after it has been converted to MP4.

By following these steps, you can customize the file location and remove the .h264 file as needed.

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.


About The Author

Muhammad Bilal

I am highly skilled and motivated individual with a Master's degree in Computer Science. I have extensive experience in technical writing and a deep understanding of SEO practices.

Scroll to Top