{"id":130036,"date":"2023-07-13T13:33:42","date_gmt":"2023-07-13T13:33:42","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=130036"},"modified":"2023-07-13T13:47:07","modified_gmt":"2023-07-13T13:47:07","slug":"raspberry-pi-motion-email-python","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-motion-email-python\/","title":{"rendered":"Raspberry Pi: Motion Detection with Email Notifications (Python)"},"content":{"rendered":"\n<p>In this project, you&#8217;ll learn how to send email notifications with the Raspberry Pi when it detects motion. We&#8217;ll program the Raspberry Pi using Python and to read from the PIR motion sensor we&#8217;ll use the <span class=\"rnthl rntliteral\">gpiozero<\/span> interface.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Tutorial.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Motion Detection with Email Notifications Python\" class=\"wp-image-130689\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Tutorial.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Tutorial.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Tutorial.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Tutorial.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Table of Contents<\/h2>\n\n\n\n<p>Throughout this tutorial, we&#8217;ll cover the following main topics:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#email-sender-account\" title=\"\">Setting Up the Sender Email Account<\/a><\/li>\n\n\n\n<li><a href=\"#circuit\" title=\"\">Wiring the Circuit<\/a> (<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-detect-motion-pir-python\/\">Raspberry Pi with PIR Motion Sensor<\/a>)<\/li>\n\n\n\n<li><a href=\"#python-script\" title=\"\">Motion Detector with Email Notifications &#8211; Python Script<\/a><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>Before continuing with this tutorial, check the following prerequisites.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Get familiar with the Raspberry Pi board\u2014if you&#8217;re not familiar with the Raspberry Pi, you can read our <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\" title=\"\"><strong>Raspberry Pi Getting Started Guide here<\/strong>.<\/a><\/li>\n\n\n\n<li>You must know how to run and create Python files on your Raspberry Pi. We like to program our Raspberry Pi via SSH using an extension on VS Code. We have a detailed tutorial about that subject: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-remote-ssh-vs-code\/\" title=\"\"><strong>Programming Raspberry Pi Remotely using VS Code (Remote-SSH)<\/strong><\/a>.<\/li>\n\n\n\n<li>Know how to use the Raspberry Pi GPIOs so that you know how to wire the circuit properly. Read the following tutorial: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pinout-gpios\/\"><strong>Raspberry Pi Pinout Guide: How to use the Raspberry Pi GPIOs?<\/strong><\/a><\/li>\n<\/ol>\n\n\n\n<p>We also have tutorials about how to send emails and how to use a PIR motion sensor that you might want to follow first:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-send-email-python-smtp-server\/\">Raspberry Pi: How to Send an Email using Python (SMTP Server)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-detect-motion-pir-python\/\">Raspberry Pi: Detect Motion using a PIR Motion Sensor (Python Script)<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Project Overview<\/h2>\n\n\n\n<p>In this project, we&#8217;ll create a motion detector with email notifications. The project has the following features:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Circuit.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Motion Sensor with Email Notifications Circuit\" class=\"wp-image-130684\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Circuit.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Circuit.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>When motion is detected, you&#8217;ll receive an alert message on your email account.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>There&#8217;s a button in the circuit so that you can enable\/disable the motion sensor. For example, turn it off when you&#8217;re in the room, and turn it on when you go out.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>There&#8217;s an LED that indicates whether the motion sensor is active (LED on) or deactivated (LED off).<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"email-sender-account\">Setting Up the Sender Email Account<\/h2>\n\n\n\n<p>We recommend creating a new email account to send the emails to your main personal email address. <strong>Do not use your main personal email to send emails via a Python script<\/strong>. If something goes wrong in your code or if by mistake you make too many requests, you can be banned or have your account temporarily disabled.<\/p>\n\n\n\n<p>We&#8217;ll use a newly created Gmail.com account to send the emails, but you can use any other email provider. The receiver email can be your personal email without any problem.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Create a Sender Email Account<\/h3>\n\n\n\n<p>Create a new email account for sending emails using a Python script. If you want to use a Gmail account, <a aria-label=\" (opens in a new tab)\" href=\"https:\/\/www.google.com\/gmail\/about\/\" target=\"_blank\" rel=\"noreferrer noopener\">go to this link<\/a> to create a new one.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"940\" height=\"602\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/02\/GMAIL-create-a-new-account.png?resize=940%2C602&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Gmail Create a new account\" class=\"wp-image-93593\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/02\/GMAIL-create-a-new-account.png?w=940&amp;quality=100&amp;strip=all&amp;ssl=1 940w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/02\/GMAIL-create-a-new-account.png?resize=300%2C192&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/02\/GMAIL-create-a-new-account.png?resize=768%2C492&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 940px) 100vw, 940px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"create-app-password\">Create an App Password<\/h3>\n\n\n\n<p>You need to create an app password so that new devices can send emails using your Gmail account. An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. <a href=\"https:\/\/support.google.com\/accounts\/answer\/185833\" target=\"_blank\" rel=\"noreferrer noopener\">Learn more about sign-in with app passwords here<\/a>.<\/p>\n\n\n\n<p>An app password can only be used with accounts that have <strong><a href=\"https:\/\/support.google.com\/accounts\/answer\/185839\" target=\"_blank\" rel=\"noopener\">2-step verification turned on<\/a><\/strong>. <\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Open your&nbsp;<a href=\"https:\/\/myaccount.google.com\/\" target=\"_blank\" rel=\"noopener\">Google Account<\/a>.<\/li>\n\n\n\n<li>In the navigation panel, select&nbsp;<strong>Security<\/strong>.<\/li>\n\n\n\n<li>Under \u201cSigning in to Google,\u201d select&nbsp;<strong>2-Step Verification<\/strong>&nbsp;&gt; <strong>Get started<\/strong>.<\/li>\n\n\n\n<li>Follow the on-screen steps.<\/li>\n<\/ol>\n\n\n\n<p>After enabling 2-step verification, you can create an app password.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Open your&nbsp;<a href=\"https:\/\/myaccount.google.com\/\" target=\"_blank\" rel=\"noopener\">Google Account<\/a>.<\/li>\n\n\n\n<li>In the navigation panel, select&nbsp;<strong>Security<\/strong>.<\/li>\n\n\n\n<li>Under \u201cSigning in to Google,\u201d select <strong>App Passwords<\/strong>.<\/li>\n<\/ol>\n\n\n\n<p>If you don&#8217;t find this option, use the search tool on that page and search for <strong>App passwords<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"724\" height=\"323\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/create-app-password-gmail.png?resize=724%2C323&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Create app password gmail\" class=\"wp-image-109736\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/create-app-password-gmail.png?w=724&amp;quality=100&amp;strip=all&amp;ssl=1 724w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/create-app-password-gmail.png?resize=300%2C134&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 724px) 100vw, 724px\" \/><\/figure><\/div>\n\n\n<ol start=\"4\"><li>In the Select app field, choose <strong>mail<\/strong>. For the device, select <strong>Other<\/strong> and give it a name, for example <em>Raspberry Pi.<\/em> Then, click on <strong>Generate<\/strong>. It will pop-up a window with a password that you&#8217;ll use on the Python script to send emails. Save that password (even though it says you won&#8217;t need to remember it) because you&#8217;ll need it later.<\/li><\/ol>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"654\" height=\"474\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/generated-app-password-gmail.png?resize=654%2C474&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Generated App password gmail\" class=\"wp-image-109742\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/generated-app-password-gmail.png?w=654&amp;quality=100&amp;strip=all&amp;ssl=1 654w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/generated-app-password-gmail.png?resize=300%2C217&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 654px) 100vw, 654px\" \/><\/figure><\/div>\n\n\n<p>Now, you should have an app password that you can use on your Python script to send emails.<\/p>\n\n\n\n<p>If you&#8217;re using another email provider, check how to create an app password. You should be able to find the instructions with a quick Google search &#8220;<strong>your_email_provider<\/strong> + create app password&#8221;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"circuit\">Raspberry Pi with PIR Motion Sensor &#8211; Wiring the Circuit<\/h2>\n\n\n\n<p>For this project, we&#8217;ll use the following components.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Board<\/a> &#8211; read <a href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-starter-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Best Raspberry Pi Starter Kits<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mini-hc-sr505-pir-motion-sensor\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Mini PIR Motion Sensor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener\" title=\"\">LED<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/pushbuttons-kit\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Pushbutton<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Breadboard<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Jumper Wires<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<p>We&#8217;ll connect the LED to <span class=\"rnthl rntcorange\">GPIO 14<\/span>, the button to <span class=\"rnthl rntcblue\">GPIO 4<\/span> and the PIR motion sensor to <span class=\"rnthl rntcyellow\">GPIO 18<\/span>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Component<\/strong><\/td><td><strong>Raspberry Pi<\/strong><\/td><\/tr><tr><td>LED<\/td><td><span class=\"rnthl rntcorange\">GPIO 14<\/span><\/td><\/tr><tr><td>Button<\/td><td><span class=\"rnthl rntcblue\">GPIO 4<\/span><\/td><\/tr><tr><td>PIR Motion Sensor<\/td><td><span class=\"rnthl rntcyellow\">GPIO 18<\/span><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1200\" height=\"697\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/motion-sensor-button-led_bb.png?resize=1200%2C697&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi with PIR Motion Sensor Wiring the Circuit\" class=\"wp-image-130687\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/motion-sensor-button-led_bb.png?w=1640&amp;quality=100&amp;strip=all&amp;ssl=1 1640w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/motion-sensor-button-led_bb.png?resize=300%2C174&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/motion-sensor-button-led_bb.png?resize=1024%2C594&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/motion-sensor-button-led_bb.png?resize=768%2C446&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/motion-sensor-button-led_bb.png?resize=1536%2C892&amp;quality=100&amp;strip=all&amp;ssl=1 1536w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"python-script\">Motion Detector with Email Notifications &#8211; Python Script<\/h2>\n\n\n\n<p>Create a new Python file called <em>motion_email_notifications.py<\/em> and copy the following code.<\/p>\n\n\n\n<p>You need to insert your sender email details and the recipient email.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete Project Details: https:\/\/RandomNerdTutorials.com\/raspberry-pi-motion-email-python\/\n\n#import necessary libraries\nfrom gpiozero import LED, Button, MotionSensor\nimport smtplib\nfrom email.message import EmailMessage\nfrom signal import pause\nfrom time import sleep\n\n#create objects to refer to the LED, the button, and the PIR sensor\nled_status = LED(14)\nbutton = Button(4)\npir = MotionSensor(18)\n\n#replace the next three lines with your credentials\nfrom_email_addr = &quot;REPLACE_WITH_SENDER_EMAIL_ADDRESS&quot;\nfrom_email_password = &quot;REPLACE_WITH_SENDER_APP_PASSWORD&quot;\nto_email_addr = &quot;REPLACE_WIH_RECIPIENT_EMAIL_ADDRESS&quot;\nemail_subject = &quot;[WARNING!] Intruder Alert!&quot;\nemail_body = &quot;Motion was detected in your room!&quot;\n\n#control variables\nmotion_sensor_status = False\nemail_sent = False\n\n#arm or disarm the PIR sensor\ndef arm_motion_sensor():\n    global email_sent\n    global motion_sensor_status\n\n    if motion_sensor_status == True:\n       motion_sensor_status = False\n       led_status.off()\n       print(&quot;Motion Sensor OFF&quot;)\n    else:\n        motion_sensor_status = True\n        email_sent = False\n        led_status.on()\n        print(&quot;Motion Sensor ON&quot;)\n\n#send email when motion is detected and the PIR sensor is armed\ndef send_email():\n    global email_sent\n    global motion_sensor_status\n\n    if(motion_sensor_status == True and email_sent == False):\n        print(&quot;Motion Detected&quot;)\n        #create a message object\n        msg = EmailMessage()\n        #set the email body\n        msg.set_content(email_body)\n        #set sender and recipient\n        msg['From'] = from_email_addr\n        msg['To'] = to_email_addr\n        #set your email subject\n        msg['Subject'] = email_subject\n        #connect to server and send email\n        #edit this line with your provider's SMTP server details\n        server = smtplib.SMTP('smtp.gmail.com', 587)\n        #comment out this line if your provider doesn't use TLS\n        server.starttls()\n        server.login(from_email_addr, from_email_password)\n        server.send_message(msg)\n        server.quit()\n        email_sent = True\n        print('Email sent')\n        sleep(5)\n        email_sent = False\n\n#assign a function that runs when the button is pressed\nbutton.when_pressed = arm_motion_sensor\n\n#assign a function that runs when motion is detected\npir.when_motion = send_email\n\npause()\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi\/motion_detection_email_notifications.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>Continue reading to learn how the code works and what changes you need to make to the script to make it work for you.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Importing libraries<\/h4>\n\n\n\n<p>You start by importing the <span class=\"rnthl rntliteral\">LED<\/span>, <span class=\"rnthl rntliteral\">Button<\/span> and <span class=\"rnthl rntliteral\">MotionSensor<\/span> components from the <span class=\"rnthl rntliteral\">gpiozero<\/span> library.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from gpiozero import LED, Button, MotionSensor<\/code><\/pre>\n\n\n\n<p>Then, import the libraries for SMTP and email-related functions.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import smtplib\nfrom email.message import EmailMessage<\/code><\/pre>\n\n\n\n<p>You also import the <span class=\"rnthl rntliteral\">pause<\/span> and <span class=\"rnthl rntliteral\">sleep<\/span> methods to add timers to the code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from signal import pause\nfrom time import sleep<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Creating the LED, Motion Sensor and Button Components<\/h4>\n\n\n\n<p>After importing the required libraries, we create <span class=\"rnthl rntliteral\">gpiozero<\/span> objects to refer to our electronic components. The <span class=\"rnthl rntliteral\">LED<\/span> is connected to <span class=\"rnthl rntcorange\">GPIO 14<\/span>, the <span class=\"rnthl rntliteral\">Button<\/span> to <span class=\"rnthl rntcblue\">GPIO 4<\/span>, and the <span class=\"rnthl rntliteral\">MotionSensor<\/span> to <span class=\"rnthl rntcyellow\">GPIO18<\/span>. If you&#8217;re using different GPIOs, adjust the code accordingly.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>#create objects to refer to the LED, the button, and the PIR sensor\nled_status = LED(14)\nbutton = Button(4)\npir = MotionSensor(18)<\/code><\/pre>\n\n\n\n<p>If you want to learn in more detail how to use those components, check the tutorials below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>LED: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-digital-outputs-python\/\" title=\"\">Control Raspberry Pi Digital Outputs with Python (LED)<\/a><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Button: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-digital-inputs-python\/\">Raspberry Pi: Read Digital Inputs with Python (Buttons and Other Peripherals)<\/a><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Motion Sensor: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-detect-motion-pir-python\/\">Raspberry Pi: Detect Motion using a PIR Sensor with Python<\/a> <\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Sender and Recipient Emails<\/h4>\n\n\n\n<p>Next, you create variables for the email address to send from, that email\u2019s app password (it&#8217;s the APP PASSWORD, not the email password, <a href=\"#create-app-password\" title=\"\">see these instructions<\/a>), and an email address to send to. As we&#8217;ve mentioned previously, we recommend using an email account that is not your primary account to send the emails.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>#replace the next three lines with your credentials\nfrom_email_addr = \"REPLACE_WITH_SENDER_EMAIL_ADDRESS\"\nfrom_email_password = \"REPLACE_WITH_SENDER_APP_PASSWORD\"\nto_email_addr = \"REPLACE_WIH_RECIPIENT_EMAIL_ADDRESS\"<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Email Subject and Body<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">email_subject<\/span> and <span class=\"rnthl rntliteral\">email_body<\/span> variables, as the names suggest, save the email subject and body. You can change the content to whatever message is suitable for your project.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>email_subject = \"&#091;WARNING!] Intruder Alert!\"\nemail_body = \"Motion was detected in your room!\"<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Control Variables<\/h4>\n\n\n\n<p>We create two control variables. The <span class=\"rnthl rntliteral\">motion_sensor_status<\/span> to know whether the motion sensor should be activated or not (we&#8217;ll change it with the press of a button). By default, it&#8217;s set to <span class=\"rnthl rntliteral\">False<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>motion_sensor_status = False<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">email_sent<\/span> variable controls whether a notification email was sent a few seconds before.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>email_sent = False<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Activate the motion sensor (function)<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">arm_motion_sensor()<\/span> function arms and disarms the motion sensor when you press the pushbutton. It also turns on and the off the LED so that you have a visual indication of whether the motion sensor is activated or not.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>#arm or disarm the PIR sensor\ndef arm_motion_sensor():\n    global email_sent\n    global motion_sensor_status\n\n    if motion_sensor_status == True:\n       motion_sensor_status = False\n       led_status.off()\n       print(\"Motion Sensor OFF\")\n    else:\n        motion_sensor_status = True\n        email_sent = False\n        led_status.on()\n        print(\"Motion Sensor ON\")<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Send Email (function)<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">send_email()<\/span> function sends an email when the sensor detects motion, as long as the sensor is armed and the <span class=\"rnthl rntliteral\">email_sent<\/span> variable is equal to <span class=\"rnthl rntliteral\">False<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>#send email when motion is detected and the PIR sensor is armed\ndef send_email():\n    global email_sent\n    global motion_sensor_status\n\n    if(motion_sensor_status == True and email_sent == False):\n        print(\"Motion Detected\")\n        #create a message object\n        msg = EmailMessage()\n        #set the email body\n        msg.set_content(email_body)\n        #set sender and recipient\n        msg&#091;'From'] = from_email_addr\n        msg&#091;'To'] = to_email_addr\n        #set your email subject\n        msg&#091;'Subject'] = email_subject\n        #connect to server and send email\n        #edit this line with your provider's SMTP server details\n        server = smtplib.SMTP('smtp.gmail.com', 587)\n        #comment out this line if your provider doesn't use TLS\n        server.starttls()\n        server.login(from_email_addr, from_email_password)\n        server.send_message(msg)\n        server.quit()\n        email_sent = True\n        print('Email sent')\n        sleep(5)\n        email_sent = False<\/code><\/pre>\n\n\n\n<p>For more details about how to set up and send an email using a Python script, check this tutorial:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-send-email-python-smtp-server\/\">Raspberry Pi: Send an Email using Python (SMTP Server)<\/a><\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Assign Functions to Events<\/h4>\n\n\n\n<p>Last, assign functions to events: the <span class=\"rnthl rntliteral\">arm_motion_sensor()<\/span> function is called when the pushbutton is pressed, and the <span class=\"rnthl rntliteral\">send_email()<\/span> function is called when motion is detected.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>#assign a function that runs when the button is pressed\nbutton.when_pressed = arm_motion_sensor\n\n#assign a function that runs when motion is detected\npir.when_motion = send_email<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">pause()<\/span> function at the end of the code keeps the script running for events to be detected.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>pause()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Save your Python file. Then run it on your Raspberry Pi. Run the following command on the directory of your project file (use the name of your file):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><em>python motion_email_notifications.py<\/em><\/code><\/pre>\n\n\n\n<p>After running the script, press the pushbutton to arm the motion sensor. The LED will light up.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Activate-Motion-Sensor.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Motion Sensor with Email Notifications - activate motion sensor\" class=\"wp-image-130683\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Activate-Motion-Sensor.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Activate-Motion-Sensor.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Then, you can test the sensor by moving your hand in front of it.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Notifications-Test.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Motion Sensor with Notifications Testing the Circuit\" class=\"wp-image-130682\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Notifications-Test.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Notifications-Test.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p> After a few seconds, you should receive a new message on your email account.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"314\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/raspberry-pi-motion-email-testing.jpg?resize=750%2C314&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Motion Sensor with Email Notifications - Receive email\" class=\"wp-image-130685\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/raspberry-pi-motion-email-testing.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/raspberry-pi-motion-email-testing.jpg?resize=300%2C126&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this project, you learned how to use a PIR motion sensor to send an email notification when motion is detected. You can trigger any other events when motion is detected besides sending an email or you can send other types of notifications like WhatsApp messages or SMS (you&#8217;ll need to use other services).<\/p>\n\n\n\n<p>For example, you can add a piezo buzzer to your alarm circuit so that when motion is detected not only is an email sent but an alarm is also sounded\u2014the <span class=\"rnthl rntliteral\">gpiozero<\/span> library comes with a component for piezzo buzzer.<\/p>\n\n\n\n<p>You can also use a relay and a photoresistor to make a security nightlight that turns on only when movement is detected in the dark\u2014the <span class=\"rnthl rntliteral\">gpiozero<\/span> library also comes with a component for a light sensor.<\/p>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful. If you want to learn more about how to control electronics using the Raspberry Pi, check the following tutorials:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\">Getting Started with Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pinout-gpios\/\">Raspberry Pi Pinout Guide<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi\/\">All our Raspberry Pi Projects and Guides<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>In this project, you&#8217;ll learn how to send email notifications with the Raspberry Pi when it detects motion. We&#8217;ll program the Raspberry Pi using Python and to read from the &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi: Motion Detection with Email Notifications (Python)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-motion-email-python\/#more-130036\" aria-label=\"Read more about Raspberry Pi: Motion Detection with Email Notifications (Python)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":130689,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[301,264,190,268],"tags":[],"class_list":["post-130036","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-0-raspberrypi","category-project","category-raspberry-pi","category-raspberry-pi-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/Raspberry-Pi-Motion-Sensor-Email-Notifications-Tutorial.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/130036","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=130036"}],"version-history":[{"count":14,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/130036\/revisions"}],"predecessor-version":[{"id":133180,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/130036\/revisions\/133180"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/130689"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=130036"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=130036"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=130036"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}