User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Send an email when a file is created

Thu Jun 18, 2015 4:08 am

I made a Raspberry Pi security camera and would like it to send me an email whenever a new video is created. The videos are saved in /home/pi/Motion and are .mpg files, if that helps. Also, I would like to find a way to delete .mpg files over 14 days old. Can someone please give me detailed instructions on how to do this?
- LightningPi(a.k.a LightningJimmy)

Heater
Posts: 13642
Joined: Tue Jul 17, 2012 3:02 pm

Re: Send an email when a file is created

Thu Jun 18, 2015 7:55 am

1) Install node.js so that you can do this in the very easy to use JavaScript language:
https://learn.adafruit.com/node-embedde ... ode-dot-js
and read this:
https://learn.adafruit.com/node-embedde ... ode-dot-js

2) Install the file watcher mode module "watchr" which can use to tell when new files are created:
https://www.npmjs.com/package/watchr
The code examples on that page show how easy iy is to do.

3) Install the nodemailer module to handle sending those emails:
https://github.com/andris9/Nodemailer
Again example code on that page shows how to do it.

Get those examples working, experiment with different things then put them together to create the program you want.

File deletion after a certain time can be done by using nodes built in file system handling library:
https://nodejs.org/api/fs.html
Again lots of example code to get you going on that page.

Good luck with your project. Come back with any questions if you get stuck.
Memory in C++ is a leaky abstraction .

User avatar
r3d4
Posts: 967
Joined: Sat Jul 30, 2011 8:21 am
Location: ./

Re: Send an email when a file is created

Thu Jun 18, 2015 9:15 am

Heater wrote:1) Install node.js so that you can do this in the very easy to use JavaScript language:
https://learn.adafruit.com/node-embedde ... ode-dot-js
and read this:
https://learn.adafruit.com/node-embedde ... ode-dot-js
If you are new to JavaScript/programing bookmark this learnxinyminutes.com/docs/javascript/ it is a good quick reference that covers lots of useful JS stuff !, and has links to more specific in-depth resources yay!

Heater
Posts: 13642
Joined: Tue Jul 17, 2012 3:02 pm

Re: Send an email when a file is created

Thu Jun 18, 2015 1:38 pm

LightningPi,

I was curious about my own advice so I put it together to see what happened.
This watches files in the ./images directory and sends a mail on any change.
Adapt as you need.
Certainly there are many ways to send mail, see the mailer module documentation and adapt for your circumstances.

Code: Select all

// Always use ES5 strict mode.
"use strict";

// Required modules 
var watchr = require('watchr');
var nodemailer = require('nodemailer');

// Create a mail transport
var transporter = nodemailer.createTransport();

// Send mail with any given data as content.
function sendMail(data) {
    console.log("Sending mail...");
    var message = JSON.stringify(data);
    console.log(message);
    transporter.sendMail({
        from: 'fred.blogs@somewhere.com',
        to: 'jane.doe@somewhere.ie',
        subject: 'Hello',
        text: "File change: " + message
    }, function (err, info) {
        if (err) {
            console.log(err);
            return;
        }
        console.log(info);
    });
}

// Watch  directories or files for changes
console.log('Watch our paths');
watchr.watch({
    paths: ['./images'],
    listeners: {
        log: function (logLevel) {
        //    console.log('a log message occured:', arguments);
        },
        error: function (err) {
            console.log('An error occured:', err);
        },
        watching: function (err, watcherInstance, isWatching) {
            if (err) {
                console.log("Watching the path " + watcherInstance.path + " failed with error", err);
            } else {
                console.log("Watching the path " + watcherInstance.path + " OK");
            }
        },
        change: function (changeType, filePath, fileCurrentStat, filePreviousStat) {
            console.log('A change event occured:');
            sendMail(arguments);
        }
    }
});
Memory in C++ is a leaky abstraction .

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Thu Jun 18, 2015 5:00 pm

Heater wrote: 2) Install the file watcher mode module "watchr" which can use to tell when new files are created:
https://www.npmjs.com/package/watchr
The code examples on that page show how easy iy is to do.
What do I have to do with watchr? What am I supposed to edit on the config?(Sorry if these problems are kind of stupid...)

EDIT: Also, I can't find/access the config, what command or whatever should I use?
Thanks for helping,
- LightningPi(a.k.a LightningJimmy)

Heater
Posts: 13642
Joined: Tue Jul 17, 2012 3:02 pm

Re: Send an email when a file is created

Thu Jun 18, 2015 6:23 pm

Not stupid at all. If you have never been there then you have never been there. We all have to start from somewhere.

Can I ask, have you ever done any programming before? It's good to know where we are starting from.

First thing is to get node.js installed as per the link to the instructions I gave at https://learn.adafruit.com/node-embedde ... ode-dot-js

At least up to the point that you can run:

$ node -v

and it tells you it's version number.

Then we can move on to the next part.
Memory in C++ is a leaky abstraction .

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Thu Jun 18, 2015 9:00 pm

I only know a bit of python and a tiny bit of HTML. I already did the first part that you mentioned.
- LightningPi(a.k.a LightningJimmy)

Heater
Posts: 13642
Joined: Tue Jul 17, 2012 3:02 pm

Re: Send an email when a file is created

Thu Jun 18, 2015 9:19 pm

In that case you should create a new directory for your project:

$ mkdir myProject

and change into it:

$ cd myProject

Then you should be able to install the required node modules:

$ npm install watchr
$ npm install nodemailer

Then copy and paste or otherwise get the code I attached above into a file called main.js

Make an images directory under that:

$ mkdir images

Then you should be able to run the program with:

$ node main.js

Now, if you open another terminal window and copy, write or whatever a file into that images directory you should see something happen in the first terminal.

Report back your progress.
Memory in C++ is a leaky abstraction .

Tom_A
Posts: 272
Joined: Fri Dec 06, 2013 8:34 am

Re: Send an email when a file is created

Thu Jun 18, 2015 9:32 pm

LightningPi wrote:I made a Raspberry Pi security camera and would like it to send me an email whenever a new video is created. The videos are saved in /home/pi/Motion and are .mpg files, if that helps. Also, I would like to find a way to delete .mpg files over 14 days old. Can someone please give me detailed instructions on how to do this?
This is all built into motion. If that's the software that you used to set up the security cam (look like it since you are using /home/pi/Motion as the directory to store videos) you can set the configuration settings to run a mailer that will send new video or image files. This is what I've been using. Take a close look at the motion configuration file.

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Thu Jun 18, 2015 10:14 pm

Tom_A wrote: This is all built into motion. If that's the software that you used to set up the security cam (look like it since you are using /home/pi/Motion as the directory to store videos) you can set the configuration settings to run a mailer that will send new video or image files. This is what I've been using. Take a close look at the motion configuration file.
Can you tell me where this part is? I can't find it.
- LightningPi(a.k.a LightningJimmy)

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Thu Jun 18, 2015 10:21 pm

Heater wrote: Then copy and paste or otherwise get the code I attached above into a file called main.js
Do I have to make it? I can't find the a file called main.js. If I have to make it, to which directory do I put it in?
- LightningPi(a.k.a LightningJimmy)

Heater
Posts: 13642
Joined: Tue Jul 17, 2012 3:02 pm

Re: Send an email when a file is created

Fri Jun 19, 2015 2:18 am

Before we continue:

Are you using the Motion software as Tom_A suggests you might be?

If so would you rather configure Motion to send email automatically?

Or do you want to continue down the path we have started of creating your own mail sending program?
Memory in C++ is a leaky abstraction .

Tom_A
Posts: 272
Joined: Fri Dec 06, 2013 8:34 am

Re: Send an email when a file is created

Fri Jun 19, 2015 4:08 am

LightningPi wrote:
Tom_A wrote: This is all built into motion. If that's the software that you used to set up the security cam (look like it since you are using /home/pi/Motion as the directory to store videos) you can set the configuration settings to run a mailer that will send new video or image files. This is what I've been using. Take a close look at the motion configuration file.
Can you tell me where this part is? I can't find it.
I wrote a guide on how to set this up here:
http://www.technicallytom.com/2013/12/1 ... pi-webcam/

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Fri Jun 19, 2015 6:46 pm

Heater wrote:Before we continue:

Are you using the Motion software as Tom_A suggests you might be?

If so would you rather configure Motion to send email automatically?

Or do you want to continue down the path we have started of creating your own mail sending program?

Yes I am using Motion, as Tom_A said. I'm going to try Tom_A's way, if it doesn't work, I'll continue.
- LightningPi(a.k.a LightningJimmy)

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Fri Jun 19, 2015 6:58 pm

Tom_A wrote: I wrote a guide on how to set this up here:
http://www.technicallytom.com/2013/12/1 ... pi-webcam/
What do I put for the "System Mail Name"?
Attachments
puttyshot.png
puttyshot.png (13.55 KiB) Viewed 4047 times
- LightningPi(a.k.a LightningJimmy)

Tom_A
Posts: 272
Joined: Fri Dec 06, 2013 8:34 am

Re: Send an email when a file is created

Fri Jun 19, 2015 10:51 pm

LightningPi wrote:
Tom_A wrote: I wrote a guide on how to set this up here:
http://www.technicallytom.com/2013/12/1 ... pi-webcam/
What do I put for the "System Mail Name"?
I think I used the domain name my website uses, however I think this may not be as important as it looks. I think this sets the addresses on mail that is sent out, however if you follow the whole guide, the address will show up as from the gmail account you are using.

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Sat Jun 20, 2015 12:49 am

Whenever I run a command that has to do with postfix(I think) I get this thingie:
warning: inet_protocols: disabling IPv6 name/address support: Address family not supported by protocol
Is this normal?

Also on your website it says
If everything is working properly:

echo "This is a test." | mail -s "Testing 1 2 3" yourname@yourmail.com

…will send a test mail to the account provided. This account does not need to be the same gMail account. The message will show up in your gMail sent messages.
I did not see any email in the sent messages nor the inbox.
Please help me fix this.

Thanks for helping,
- LightningPi(a.k.a LightningJimmy)

Tom_A
Posts: 272
Joined: Fri Dec 06, 2013 8:34 am

Re: Send an email when a file is created

Sat Jun 20, 2015 3:06 am

you might try typing mail or sudo mail to see if you are getting any failed sent messages. I think they could possibly end up under the user motion as well.
Are you using 2 step authentications on your gmail account?

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Sat Jun 20, 2015 3:36 am

Tom_A wrote: Are you using 2 step authentications on your gmail account?
No I'm not.

What happens is this:
send-mail: warning: inet_protocols: disabling IPv6 name/address support: Address family not supported by protocol
postdrop: warning: inet_protocols: disabling IPv6 name/address support: Address family not supported by protocol
Nothing else follows and I have to manually stop it.
- LightningPi(a.k.a LightningJimmy)

Tom_A
Posts: 272
Joined: Fri Dec 06, 2013 8:34 am

Re: Send an email when a file is created

Sun Jun 21, 2015 6:09 pm

Not sure why you are getting this error. Here is my entire /etc/postfix/main.cf file. Compare it to what you have and see if anything looks like it might be causing the problem. I think there may have been some changes to the default configuration causing this problem.

Code: Select all

# See /usr/share/postfix/main.cf.dist for a commented, more complete version


# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = Livingroom
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = technicallytom.com, Livingroom, localhost.localdomain, localhost
relayhost = smtp.localdomain
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = ipv4

relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_CAfile = /etc/postfix/cacert.pem
smtp_use_tls = yes

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Mon Jun 29, 2015 4:34 pm

Sorry for the late response, I went camping for a week.

I fixed that part but it still doesn't work. Do you have any idea what this means:
You have new mail in /var/mail/pi

Also in /etc/postfix/sasl_passwd I should put this:
[smtp.gmail.com]:587 ___@gmail.com:myPassword
right?
- LightningPi(a.k.a LightningJimmy)

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Mon Jun 29, 2015 4:44 pm

Also when I do "mail", the messages showup as Undelivered mail. Is that normal?

Update:
When I tried I relieved an email titled "Google Account: sign-in attempt blocked" a minute later. Does this have to do with why it didn't work?
- LightningPi(a.k.a LightningJimmy)

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Mon Jun 29, 2015 5:01 pm

NEVER MIND:
I fixed the problem. I had to enable access for less secure apps here: https://www.google.com/settings/security/lesssecureapps
Add to your guide that link at tell people to change it to "on". Thanks for helping!
- LightningPi(a.k.a LightningJimmy)

User avatar
LightningPi
Posts: 24
Joined: Wed Mar 26, 2014 3:00 am

Re: Send an email when a file is created

Mon Jun 29, 2015 5:06 pm

Two more problems:

On your website it says
To have the software email photos of movement, you need to un-comment and edit the “on picture save line.” to read :

on_picture_save echo ‘Webcam Alert’ | mail -a %f -s “Webcam Alert” youremail@youremailprovider.com
Can you give me the code around that area in /etc/motion/motion.conf because I don't understand what part you change.
BTW, I will use "on_movie_end" instead of "on_picture_save" so if you can, please give me the code for this section:
# Command to be executed when a movie file (.mpg|.avi) is created. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_start value

# Command to be executed when a movie file (.mpg|.avi) is closed. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_end value

# Command to be executed when a camera can't be opened or if it is lost
# NOTE: There is situations when motion doesn't detect a lost camera!
# It depends on the driver, some drivers don't detect a lost camera at all
# Some hang the motion thread. Some even hang the PC! (default: none)
; on_camera_lost value

Also:
How do I "unsubscribe" from the RPi. If I made a new email just for that and wanted to remove the RPi from sending to my old email, how would I do it?
- LightningPi(a.k.a LightningJimmy)

Tom_A
Posts: 272
Joined: Fri Dec 06, 2013 8:34 am

Re: Send an email when a file is created

Mon Jun 29, 2015 10:20 pm

LightningPi wrote:Two more problems:

On your website it says
To have the software email photos of movement, you need to un-comment and edit the “on picture save line.” to read :

on_picture_save echo ‘Webcam Alert’ | mail -a %f -s “Webcam Alert” youremail@youremailprovider.com
Can you give me the code around that area in /etc/motion/motion.conf because I don't understand what part you change.
BTW, I will use "on_movie_end" instead of "on_picture_save" so if you can, please give me the code for this section:
# Command to be executed when a movie file (.mpg|.avi) is created. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_start value

# Command to be executed when a movie file (.mpg|.avi) is closed. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_end value

# Command to be executed when a camera can't be opened or if it is lost
# NOTE: There is situations when motion doesn't detect a lost camera!
# It depends on the driver, some drivers don't detect a lost camera at all
# Some hang the motion thread. Some even hang the PC! (default: none)
; on_camera_lost value
The code for on_movie_end should be the same. You want it to send an email just like you would if you were sending an email with just a photo. The %f will send a video instead since it's being accessed on the on_movie_end line. So, looking at the entire line, we have:
echo - This is going to pass the body text along to the mail command. If you just used echo from the terminal, it would print to screen, but we use the pipe character to send the output to the mail command.
"Webcam Alert" - The body text of the email piped to the mail command.
mail - send an email
-a - include an attachment
%f - path to the file to be attached.
-s - subject of email follows this.
"Webcam Alert" - This is the subject. You can change the subject and the body text of the email to whatever you want.
youremail@youremailprovider.com - and finally your email address.

I'll put a note in about the issue you had with sending an email, however that setting is not available if you use two step authentication. You need to create an app specific password instead. I highly recommend using two step authentication on email accounts whenever possible. This is something that I think was changed in the way gmail works after I wrote the guide. They are probably trying to just make gmail as secure as possible when people don't opt for two step authentication, however 2 step authentication is still going to be more secure.

Return to “General discussion”