Now, you need to create the Python program. To do this, copy the code below into a file called “”. On Mac / Linux you can use the “nano” editor, on Windows, it is probably easiest to make the file using the Python editor 'IDLE” which is available from the Python program group on your start menu.

import time
import serial
import smtplib

TO = '[email protected]'
GMAIL_USER = '[email protected]'
GMAIL_PASS = 'putyourpasswordhere'

SUBJECT = 'Intrusion!!'
TEXT = 'Your PIR sensor detected movement'
ser = serial.Serial('COM4', 9600)

def send_email():
    print("Sending Email")
    smtpserver = smtplib.SMTP("",587)
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = 'To:' + TO + '\n' + 'From: ' + GMAIL_USER
    header = header + '\n' + 'Subject:' + SUBJECT + '\n'
    print header
    msg = header + '\n' + TEXT + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, TO, msg)
while True:
    message = ser.readline()
    if message[0] == 'M' :

Before you run the Python program, there are some configuration changes that you need to make. These are all up near the top of the file.

The program assumes that the emails are being set from a gmail account. So, if you don't have one, you might like to make yourself one, even if it is just for this project.

Change the email address next to “TO” to the email that you want to receive the notifications. This does not have to be your email address, but probably will be.

Change the email address next to “GMAIL_USER” to the email address of your gmail address and alter the password on the next line to the password you use to retrieve your emails.

If you want to, you can also change the subject line and text of the message to be sent, on the lines that follow.

You will also need to set the serial port of the Arduino by editing the line below:

ser = serial.Serial('COM4', 9600)
For Windows, this will be something like “COM4” for Mac and Linux, something like “/dev/tty.usbmodem621”. You can find this by openning the Arduino IDE and in the bottom right corner, it will show you the port that is connected to the Arduino.

When you have made these changes, you can run the program from Command Prompt / Terminal with the command:


When a movement is triggered you should get some trace like this and shortly after an email will arrive in your inbox.

Notice also the “Too soon” messages.

This guide was first published on Feb 28, 2013. It was last updated on Mar 08, 2024.

This page (Python Code) was last updated on Feb 28, 2013.

Text editor powered by tinymce.