dj_janker
Posts: 59
Joined: Thu Jan 08, 2015 6:15 pm

Sending attached images (last 5 created) by e-mail

Sun Oct 18, 2015 7:12 am

Hi,
I´m noob in python and I need to create a script to send the last 5 snapshots created by a external camera by email.
I find in google this code that I think it´s possible to adapt it to my need.

Code: Select all

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
 
fromaddr = "YOUR EMAIL"
toaddr = "EMAIL ADDRESS YOU SEND TO"
 
msg = MIMEMultipart()
 
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE EMAIL"
 
body = "TEXT YOU WANT TO SEND"
 
msg.attach(MIMEText(body, 'plain'))
 
filename = "NAME OF THE FILE WITH ITS EXTENSION"
attachment = open("PATH OF THE FILE", "rb")
 
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
 
msg.attach(part)
 
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "YOUR PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
The path where the images are saved it´s:

Code: Select all

pi@raspberrypi /usr/share/nginx/www/tmp/camera_records/cam1 $ 
The format of the images are saved it´s:

Code: Select all

 2015-10-17_19:51:06.jpg  2015-10-17_19:51:08.jpg  2015-10-17_19:51:10.jpg
2015-10-17_19:51:07.jpg  2015-10-17_19:51:09.jpg
Somebody could help me to adapt the code, please?

Thanks

dj_janker
Posts: 59
Joined: Thu Jan 08, 2015 6:15 pm

Re: Sending attached images (last 5 created) by e-mail

Sun Oct 18, 2015 12:28 pm

finally I´m trying to use this script:

Code: Select all

#!/usr/bin/env python
# encoding: utf-8
"""
python_3_email_with_attachment.py
Created by Robert Dempsey on 12/6/14.
Copyright (c) 2014 Robert Dempsey. Use at your own peril.

This script works with Python 3.x

NOTE: replace values in ALL CAPS with your own values
"""

import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

def main():
    sender = 'YOUR GMAIL ADDRESS'
    gmail_password = 'YOUR GMAIL PASSWORD'
    recipients = ['EMAIL ADDRESSES HERE SEPARATED BY COMMAS']
    
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'EMAIL SUBJECT'
    outer['To'] = COMMASPACE.join(recipients)
    outer['From'] = sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    # List of attachments
    attachments = ['FULL PATH TO ATTACHMENTS HERE']

    # Add the attachments to the message
    for file in attachments:
        try:
            with open(file, 'rb') as fp:
                msg = MIMEBase('application', "octet-stream")
                msg.set_payload(fp.read())
            encoders.encode_base64(msg)
            msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
            outer.attach(msg)
        except:
            print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
            raise

    composed = outer.as_string()

    # Send the email
    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as s:
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(sender, gmail_password)
            s.sendmail(sender, recipients, composed)
            s.close()
        print("Email sent!")
    except:
        print("Unable to send the email. Error: ", sys.exc_info()[0])
        raise

if __name__ == '__main__':
    main()
from: https://gist.github.com/rdempsey/22afd4 ... achment.py

The problem is when I try to run it, I receive this message:

Code: Select all

pi@raspberrypi ~ $ sudo python snapshotmail.py
('Unable to send the email. Error: ', <type 'exceptions.AttributeError'>)
Traceback (most recent call last):
  File "snapshotmail.py", line 64, in <module>
    if __name__ == '__main__': main()
  File "snapshotmail.py", line 52, in main
    with smtplib.SMTP('smtp.gmail.com', 587) as s:
AttributeError: SMTP instance has no attribute '__exit__'
any idea?

for the PATH WHERE THE IMAGES ARE SAVED, I think to use this variable:

Code: Select all

find /usr/share/nginx/www/tmp/camera_records/cam1 . -mmin -10
to try send the last 5 photos created in the last minute?. Do you think that´s will work?

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Sending attached images (last 5 created) by e-mail

Sun Oct 18, 2015 12:54 pm

Are you running the script in Python 2?

Using the "with" context manager was, I think, only added to smtplip.SMTP in Python 3.

Try re-running in Python 3.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

dj_janker
Posts: 59
Joined: Thu Jan 08, 2015 6:15 pm

Re: Sending attached images (last 5 created) by e-mail

Sun Oct 18, 2015 1:41 pm

elParaguayo wrote:Are you running the script in Python 2?

Using the "with" context manager was, I think, only added to smtplip.SMTP in Python 3.

Try re-running in Python 3.
I have the same error:

Code: Select all

pi@raspberrypi ~ $ sudo python3 snapshotmail.py
Unable to send the email. Error:  <class 'AttributeError'>
Traceback (most recent call last):
  File "snapshotmail.py", line 64, in <module>
    main()
  File "snapshotmail.py", line 52, in main
    with smtplib.SMTP('smtp.gmail.com', 587) as s:
AttributeError: __exit__

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Sending attached images (last 5 created) by e-mail

Sun Oct 18, 2015 1:47 pm

I still think this is the issue: http://stackoverflow.com/questions/2788 ... with-block

i don't know what version of python 3 you've got installed but, if it isn't python 3.3 or later, you can just rewrite the code to open and close the connection yourself.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

dj_janker
Posts: 59
Joined: Thu Jan 08, 2015 6:15 pm

Re: Sending attached images (last 5 created) by e-mail

Sun Oct 18, 2015 4:03 pm

elParaguayo wrote:I still think this is the issue: http://stackoverflow.com/questions/2788 ... with-block

i don't know what version of python 3 you've got installed but, if it isn't python 3.3 or later, you can just rewrite the code to open and close the connection yourself.
ok, I have installed python 3.4 and now the script works ok ;) ;)

Now I need to know how could I include in the path file de correct command to send the last 5 captures saved in it.
Any idea?

dj_janker
Posts: 59
Joined: Thu Jan 08, 2015 6:15 pm

Re: Sending attached images (last 5 created) by e-mail

Mon Oct 19, 2015 4:44 pm

In the script I need to add the paht to attachments:

Code: Select all

 # List of attachments attachments = ['FULL PATH TO ATTACHMENTS HERE']
The path where de snapshots going saving it´s:

Code: Select all

/usr/share/nginx/www/tmp/camera_records/cam1
It would be possible to use a varible filename to send the snapshot saved in the actual moment?:

Code: Select all

/usr/share/nginx/www/tmp/camera_records/cam1/(date +"%Y-%m-%d"_"%T").jpg
if isn´t valid, what command could I use for this?

Thanks


User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Sending attached images (last 5 created) by e-mail

Tue Oct 20, 2015 11:41 am

How are you currently saving the snapshots? i.e. is there a template that the file names currently use?
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

dj_janker
Posts: 59
Joined: Thu Jan 08, 2015 6:15 pm

Re: Sending attached images (last 5 created) by e-mail

Tue Oct 20, 2015 12:54 pm

elParaguayo wrote:How are you currently saving the snapshots? i.e. is there a template that the file names currently use?
Hi, I have a domotic system where I have installed a ip doorbell.
When somebody push de doorbell the camera take 5 snapshots (1 every second) and save them here:

Code: Select all

/usr/share/nginx/www/tmp/camera_records/cam1
The format of this snapshots it´s: yyyy-mm-dd_H:M:S.jpg (i.e.: 2015-10-20_14:56-18.jpg)

I would like to receive the last 5 snapshots saved.
Any idea how could adapt the script to do it?

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Sending attached images (last 5 created) by e-mail

Tue Oct 20, 2015 1:19 pm

I think my solution would be pretty ugly, but you may be able to do it like this:

Code: Select all

import os
photodir = "/usr/share/nginx/www/tmp/camera_records/cam1"
dated_files = [(os.path.getctime(photo), os.path.abspath(photo)) 
               for photo in os.listdir(photodir) if photo.lower().endswith('.jpg')]
dated_files.sort()
dated_files.reverse()
last_five = [pic[1] for pic in dated_files[:5]]
This is untested and is based on this answer on Stack Overflow.

the dated_files line creates a list of tuples in the form of (creation date of photo, full filepath to photo). The code then sorts this by the creation date (as it's the first value in the tuple) and then reverses this list so the latest files are first. Lastly, I create a new list with just the filepaths for the first 5 photos in the dated_files list, which should be the latest photos.

NB if you edit photos in the folder or changer the modified date, this may impact this script. You could try running it as a separate script and just add "print(last_five)" at the end and see what comes out.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Return to “Python”