Set Motion as e-mailing Security Camera

Read also: https://www.puolanka.org/goto/sent-mail-kansio-nakyviin-thunderbird-sahkopostiohjelmassa/

https://www.puolanka.org/goto/how-to-get-motion-take-sheduled-snapshot-kuinka-saada-motion-ottamaan-ajastettu-otos/

1. Install Mutt email program

sudo apt-get install mutt cyrus-common libsasl2-2 libsasl2-modules libsasl2-modules-db imagemagick img2pdf

mkdir -p ~/.mutt/cache/headers
mkdir ~/.mutt/cache/bodies
touch ~/.mutt/certificates

Edit: 15.4.2025: Old instructions does not work anymore for mutt so here is new instructions for mutt

2. Make a .muttrc file

# ================ IMAP =============
set editor = "nano" # Set your favourite editor.
set edit_headers = yes # See the headers when editing
set charset = UTF-8 # value of $LANG; also fallback for send_charset
set imap_user = johndoe@jotain.com # use real user
set imap_pass = password-here # use real password
set spoolfile = imaps://imap-server-here/INBOX # use real imap server
set folder = imaps://imap-server-here/ # use real imap server
set record="imaps://imap-server-here/Sent Mail" # use real imap server
set postponed="imaps://imap-server-here/Drafts" # use real imap server
set mbox="imaps://imap-server-here/All Mail" # use real imap server
set header_cache = "~/.mutt/cache/headers"
set message_cachedir = "~/.mutt/cache/bodies"
set certificate_file = "~/.mutt/certificates"
# ================ SMTP ===================

## Send options.
set smtp_url=smtps://email-address@jotain.com:password-here@smtp-server-here:465/ # use real smtp server
set realname='User X' # use real name
set from=johndoe@jotain.com # use real address
set hostname="mutt@mutt" # use some hostname
set signature="John Doe" # # use some name
# Connection options
set ssl_force_tls = yes
unset ssl_starttls
set use_from = yes
set copy = no

# ============================================
## After installing Mutt, there need to run Mutt via command line first and write and send a test email for getting sertificates.
# ============================================

# If getting an authentication error when sending an attachment, install postifix package and choose ”local” as internet operator.

==============================================

3. Make two folders

mkdir -p $HOME/motion
mkdir -p $HOME/Kuvat/posti

4. Install motion

sudo apt install motion

Edit /etc/motion/motion.conf file and make two scripts where the first script lauches Mutt if Motion has created pictures.

=============================================
check-motion-folder script

#!/bin/bash
# RJP 15.4.2025 loop test if motion folder has pictures
# Gap in seconds of no motion detected that triggers the end of an event.
#event_gap 30
## /home/username/motion is the path for motion pictures
# Target directory for pictures, snapshots and movies
#target_dir /home/username/motion
# Picture output configuration parameters
#################################################
# Output pictures when motion is detected
#picture_output off
#################################################
# Create movies of motion events.
#movie_output on
#################################################
while true; do
if [ -z "$( ls -A '/home/username/motion' )" ]; then ## replace username using real user name
echo "Empty"
else
echo "Not Empty"
#./run-mutt
./frefress-motion-folder ## if there has no internet connection
# creating backup from $HOME/motion daily

##./run-mutt-pdf ## a good option, but filesize can be large
./run-mutt-video

fi
sleep 50
done

=============================================

run-mutt script

#!/bin/bash
aika=$(date "+%F-%H-%M")
mkdir -p $HOME/Kuvat/posti
mv $HOME/motion/*.jpg $HOME/Kuvat/posti && cd $HOME/Kuvat/posti && convert -append *.jpg valvontakuva.jpg
mutt -s "Valvontakuvia" -a $HOME/Kuvat/posti/valvontakuva.jpg -- email-address@jotain.com < /dev/null sleep 1 && mv $HOME/Kuvat/posti $HOME/Kuvat/posti-$aika ## replace email-address@jotain.com using real email-address

=============================================

If imagemagick makes a too tall or wide picture, it can not convert it as a one picture, so better to convert pictures to pdf-file.

run-mutt-pdf script

#!/bin/bash
# RJP 17.4.2025 run mutt if pictures are detected
# sendind as pdf if imagemagick chokes
aika=$(date "+%F-%H-%M")
mkdir -p $HOME/Kuvat/posti
mv $HOME/motion/*.jpg $HOME/Kuvat/posti && img2pdf $HOME/Kuvat/posti/*.jpg -o $HOME/Kuvat/posti/valvontakuva.pdf && sleep 3 && \
mutt -s "Valvontakuvia" -a $HOME/Kuvat/posti/valvontakuva.pdf -- email-address@jotain.com < /dev/null && sleep 1 && \ rm $HOME/Kuvat/posti/valvontakuva.pdf && sleep 1 && mv $HOME/Kuvat/posti $HOME/Kuvat/posti-$aika ## replace email-address@jotain.com using real email-address

=============================================

The best option is to use video, as /etc/motion/motion.conf file´s basic settings.

run-mutt-video script

#!/bin/bash
# RJP 21.4.2025 run mutt if pictures are detected
# sending video.mkv file
#
aika=$(date "+%F-%H-%M")
mkdir -p $HOME/Kuvat/posti
mv $HOME/motion/*.mkv $HOME/Kuvat/posti && mv $HOME/Kuvat/posti/*.mkv $HOME/Kuvat/posti/valvontavideo.mkv && sleep 3 && \
mutt -s "Valvontavideo" -a $HOME/Kuvat/posti/valvontavideo.mkv -- email-address@jotain.com < /dev/null && sleep 1 && \ mv $HOME/Kuvat/posti $HOME/Kuvat/posti-$aika sleep 30 ## replace email-address@jotain.com using real email-address

# ===========================================
Tip: # Use movie_filename %t-%v-%Y%m%d%H%M setting in /etc/motion.motion.conf file.
# (File name(without extension) for movies relative to target directory
# movie_filename %t-%v-%Y%m%d%H%M%S )
==============================================
Edit 23.4.2025: Better scripts for emailing videos!

Scripts-for-Email-video.zip

run-mutt-video2 script

#!/bin/bash
# RJP 23.4.2025 run mutt if pictures are detected
# sending video.mkv file
#
aika=$(date "+%F-%H-%M")
mkdir -p $HOME/Kuvat/posti
mv $HOME/motion/*.mkv $HOME/Kuvat/posti && mv $HOME/Kuvat/posti/*.mkv $HOME/Kuvat/posti/valvontavideo-$aika.mkv && sleep 3 && \
mutt -s "Valvontavideo" -a $HOME/Kuvat/posti/valvontavideo-$aika.mkv -- email-address@jotain.com < /dev/null && sleep 1 && \ mv $HOME/Kuvat/posti $HOME/Kuvat/posti-$aika && sleep 30 ## replace email-address@jotain.com using real email-address

PS. WordPress shows codes wrong, so look codes from an attacment!

#===========================================

5. Set the scripts executable and add check-motion-folder to the startup if needed.

chmod +x run-mutt
chmod +x run-mutt-pdf
chmod +x run-mutt-video
chmod +x run-mutt-video2
chmod +x frefress-motion-folder
chmod +x start-motion
chmod +x stop-motion
chmod +x stop-motion
chmod +x loop-run
chmod +x stage1
chmod +x stage2
chmod +x check--run-loop-process-state

To test if the script is running

check-process-state scripti

#!/bin/bash
# RJP 18.4.2025 check-motion-folder running test
x-terminal-emulator -e /bin/bash -c '(ps -ef|grep -v grep|grep check-motion-folder > /dev/null && echo "check-motion-folder is running" || echo "check-motion-folder is not running") ; exec bash' && read -p \"
#################################################
########## running test ######################
#################################################\"" &

#!/bin/bash
# RJP 22.4.2025 run-loop running test
x-terminal-emulator -e /bin/bash -c '(ps -ef|grep -v grep|grep loop-run > /dev/null && echo "loop-run is running" || echo "loop-run is NOT running") ; exec bash' && read -p \"
#################################################
########## running test ######################
#################################################\"" &

#==========================================

Stop check-motion-folder script and loop-run script

#!/bin/bash
killall check-motion-folder
killall loop-run

#=========================================

start-motion script

#!/bin/bash
# RJP 18.4.2025 start motion manually if is not set in rc.local , etc
x-terminal-emulator -e /bin/bash -c "sudo motion && read -p \"
#################################################
########## motion stopped ######################
#################################################\"" &

#===========================================

stop-motion script

#!/bin/bash
# RJP 18.4.2025 stop motion manually
x-terminal-emulator -e /bin/bash -c "sudo killall motion && read -p \"
#################################################
########## motion should be stopped ######################
#################################################\"" &

#============================================
# Jos haluat käynnistää motionin tavallisena käyttäjänä, muokkaa sudoers-tiedostoa kuten
# username-here ALL=(ALL) NOPASSWD: /usr/bin/motion # toimii komentosarjoilla, joissa on "sudo"
#============================================
jos Internet-yhteyttä ei ole, luo varmuuskopio $HOME/motionista päivittäin.
Tämä vaihtoehto on otettava käyttöön kommentoimalla (poistamalla #) check-motion-folder-skriptistä (./frefress-motion-folder).

#============================================

frefress-motion-folder script

#!/bin/bash
# RJP 19.4.2025 # ./frefress-motion-folder ## if there has no internet connection
# creating backup from $HOME/motion daily
aika=$(date "+%Y-%m-%d")
cd $HOME/motion && \
ls -l | awk '{print $6,$7,$8,$9}' && \
stat -c %y $HOME/motion | cut -d" " -f1 > /tmp/vanha && \
date "+%Y-%m-%d" > /tmp/nykyinen && \
pwd && \
if [[ $(cat /tmp/vanha) == $(cat /tmp/nykyinen) ]]
then
echo "today created motion folder"
else
echo "old motion folder, creating new and backup from old"
mv $HOME/motion $HOME/motion-$aika && mkdir -p $HOME/motion
fi

#=============================================

Possible problems!

Always is a possibility that your email box is full or you have a network problem, so then is better to use loop script which resets folders about every minutes if needed.

=============================================

loop-run script

#!/bin/bash
# RJP 22.4.2025 looping two scripts every 30 seconds
# This scipt is controlling stage 1 and stage2 scripts
# 23.4.2025 sleep added to run-mutt-video file
while true; do
killall stage2
./stage1
echo "stage1"
sleep 30 # if 30 seconds is not enough to get full video to email, so add time to sleep command
killall stage1
./stage2
echo "stage2"
done

========================================

stage1 script

#!/bin/bash
# RJP 22.4.2025 If there has some network or sending problems
# stage1 and stage2 scripts clears and re-creates sending process
aika=$(date "+%F-%H-%M-%S")
mkdir -p $HOME/motion
mkdir -p $HOME/Kuvat/posti
if [ -z "$( ls -A '/home/usename/motion' )" ] ## replace username using real user name
then
echo "Empty"
else
echo "Not Empty"
./run-mutt-video
mv $HOME/motion $HOME/motion-$aika
mv $HOME/Kuvat/posti $HOME/Kuvat/posti-$aika
sleep 2
mkdir -p $HOME/motion
mkdir -p $HOME/Kuvat/posti
sleep 1
fi

=====================================

stage2 script

#!/bin/bash
# RJP 22.4.2025 If there has some network or sending problems
# stage1 and stage2 scripts clears and re-creates sending process
aika=$(date "+%F-%H-%M-%S")
mkdir -p $HOME/motion
mkdir -p $HOME/Kuvat/posti
if [ -z "$( ls -A '/home/username/Kuvat/posti' )" ] ## replace username using real user name
then
echo "Empty"
else
echo "Not Empty"
./run-mutt-video
mv $HOME/motion $HOME/motion-$aika
mv $HOME/Kuvat/posti $HOME/Kuvat/posti-$aika
sleep 2
mkdir -p $HOME/motion
mkdir -p $HOME/Kuvat/posti
sleep 1
fi

Email-Camera-Scripts-zip

#!/bin/bash
# RJP 25.4.2025 backup and send all videos via cron script
# https://www.linux.fi/wiki/Komentojen_ajastaminen
# https://netisto.fi/oppaat/linux/18.htm
aika=$(date "+%F-%H-%M-%S")
mkdir -p $HOME/BACKUP
sleep 1
find $HOME/Kuvat -iname "posti*" -exec mv -t $HOME/BACKUP {} +
sleep 5
tar cjf kaikkivideot-$aika.tar.bz2 $HOME/BACKUP
sleep 20
mutt -s "kaikkivideot" -a kaikkivideot-$aika.tar.bz2 -- email-address@jotain.com < /dev/null && \ sleep 60 && \ mv $HOME/BACKUP $HOME/BACKUP-$aika

https://www.linux.fi/wiki/Komentojen_ajastaminen

https://netisto.fi/oppaat/linux/18.htm

Esimerkki crontab ohjelman käytöstä:

crontab -e
.... johon lisätty rivit
# suorittaa komennon joka päivä kello 7
0 7 * * * export DISPLAY=:0.0 && /home/usename/kaikkivideot.sh

###################################
### OLD instructions from year 2015 ###
###################################

set imap_user = from_my@gmail.com
set imap_pass = verygoodpasswordhere

set smtp_url = smtp://from_my@smtp.gmail.com:587/
set smtp_pass = verygoodpasswordhere
set from = from_my@gmail.com
set realname = seuritycamera

set folder = imaps://imap.gmail.com:993
set spoolfile = "+INBOX"
set postponed="+[Gmail]/Drafts"

set header_cache=~/.mutt/cache/headers
set message_cachedir=~/.mutt/cache/bodies
set certificate_file=~/.mutt/certificates

set move = no
set record = '+Sent'

3. Test Mutt before installing Motion and then install Motion

sudo apt install motion

Add yourself to the motion group

sudo adduser myself motion

Configure Motion

gksu pluma /etc/default/motion

# set to 'yes' to enable the motion daemon
start_motion_daemon=yes

gksu pluma /etc/motion/motion.conf

... edit these lines

--------------------------------
# Minimum time in seconds between capturing picture frames from the camera.
# Default: 0 = disabled - the capture rate is given by the camera framerate.
# This option is used when you want to capture images at a rate lower than 2 per second.
minimum_frame_time 1
--------------------------------
# Target base directory for pictures and films
# Recommended to use absolute path. (Default: current working directory)
target_dir /path/motion
--------------------------------
# Command to be executed when a motion frame is detected (default: none)
on_motion_detected /home/username/.startup.sh
--------------------------------

4. Make a startup script

#! /bin/sh

Make the script executable

chmod a+x /home/username/.startup.sh

#! /bin/sh
TIMESTAMP=$(date "+%F-%H-%M-%S")

find /path/motion -iname "*.swf" -exec mv {} /path/allvideos \; && sleep 30 && genisoimage -o /path/toemail/video$TIMESTAMP.iso /path/allvideos && mutt -z -a /path/toemail/video$TIMESTAMP.iso -s "Security videos" -- to_some_email@gmail.com from_my@gmail.com < /dev/null

Make the script executable

chmod a+x /home/username/.mutt.sh

/path/motion
/path/allvideos
/path/toemail

Set the permissions for the folders
sudo chmod 775 /path/foldername

6. Add Motion to the startup applications and or crontab

PS. emails comes always when Motion has react!

WordPress shows some lines wrong, so use this document.

See also Motion live stream via browser