User avatar
joseplaselva
Posts: 60
Joined: Tue Oct 04, 2016 4:45 am

Sending by mail image files from a folder

Sun Oct 15, 2017 2:44 pm

Hi, I have a folder ( USB stick ) containing jpg files , I want, if it is possible do the folowing actions.
Select a file from this folder ( the oldest )
Send it by mail
and after succes eliminate it
take the folowing one amd make the same procedure until there is no file left...

Exist a way to do it inside a python script?
Thanks in advance for your allways valuable answerds

User avatar
MrYsLab
Posts: 74
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: Sending by mail image files from a folder

Sun Oct 15, 2017 7:17 pm

Step 1. Sort the files in your directory so that the oldest shows first

Code: Select all

import os

search_dir = "PUT YOUR FULL DIRECTORY PATH HERE"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))
for f in files:
    print(f)
Step 2. In the for loop, send out each file as an attachment
You can find information on how to do this here: https://stackoverflow.com/questions/336 ... ttachments

Step 3. Remove the file from the directory

Code: Select all

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
    else:
        raise ValueError("file {} is not a file or dir.".format(path))

User avatar
joseplaselva
Posts: 60
Joined: Tue Oct 04, 2016 4:45 am

Re: Sending by mail image files from a folder

Tue Oct 17, 2017 1:15 pm

Thanks a lot for your early reply, it helps me a lot , for the first part to read folder runs perfect , but when I try to send by mail something rare occurr. Give a look at this code

Code: Select all

for f in files:
    missedpic = missedpic + 1
    timenu= str(time.strftime("%A %y-%b-%d"))
    texmed = "Missed Pics " + timenu + " (pic " + str(missedpic) + "/" + str(nrpics) + ")"
    datum = f[16:26]
    tid =  f[26:32]
    time = tid[0:3]
    minut = tid[3:6]
    jpgnam = datum + time +":"+minut
    texte= "picture : " + jpgnam
    
    mail = MIMEMultipart()
    mail['Subject'] = str(texmed) # "Pictures from home"
    mail['From'] = fromaddr
    mail['To'] = toaddr
    mail.attach(MIMEText(texte, 'plain'))

    jpg_file=f
    attachment = open(jpg_file, 'rb')
    image=MIMEImage(attachment.read())
    attachment.close()
    mail.attach(image)
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "pasword")
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()
the first mail goes well but when prepare the second a Error happens :

timenu= str(time.strftime("%A %y-%b-%d"))
AttributeError: 'str' object has no attribute 'strftime'

Why runs well the first time and not the second ??????

I have ben testing in a external editor as:

Code: Select all

for x in xrange(4):
    timenu = str(time.strftime("%A %y-%b-%d "))

#dagtid = str(time.strftime("%y-%b-%d_(%H:%M)"))
    texmed = "Missed Pics "+ timenu
    print texmed
and it runs perfectly, why not inside the script in the Raspi

User avatar
joseplaselva
Posts: 60
Joined: Tue Oct 04, 2016 4:45 am

Re: Sending by mail image files from a folder

Tue Oct 17, 2017 1:39 pm

Sorry forget the last reply , it was my fault because somewhere before in the script I was assigning a string to a variable time... thats why.
I folow testing.
Thanks for your valuable help

User avatar
joseplaselva
Posts: 60
Joined: Tue Oct 04, 2016 4:45 am

Re: Sending by mail image files from a folder

Tue Oct 17, 2017 1:44 pm

Its works perfectly folowing your valuable indications.
Thaks a lot

User avatar
MrYsLab
Posts: 74
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: Sending by mail image files from a folder

Tue Oct 17, 2017 2:17 pm

My pleasure.

User avatar
joseplaselva
Posts: 60
Joined: Tue Oct 04, 2016 4:45 am

Re: Sending by mail image files from a folder

Wed Oct 18, 2017 11:02 am

Hi, here I am again with a question for a new problem.
In my python script I use the folowing code to write in a text file all the procedures of the script to check logical errors:

Code: Select all

with open('./log.txt', 'a') as log_txt:
    timenow = str(time.strftime("%H:%M:%S"))   
    log_txt.write(timenow + "FILES IN PENDRIVE = " + str(nrpics))
When I use the code you told me for read the Pendrive content:

Code: Select all

search_dir = "/media/pendrive"
nrpics = 0


os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, fil) for fil in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))
for fil in files:
    nrpics = nrpics + 1
It happens that a copy of the text file appears inside the pendrive folder and nothing is writed in the original text file in home directory....
Why thuis rare behaviour? I'm doing somethig wrong ?
Thanks for some help

User avatar
MrYsLab
Posts: 74
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: Sending by mail image files from a folder

Wed Oct 18, 2017 1:20 pm

I am not sure I totally understand your problem, but perhaps you should call log_txt.close() to flush the file.

User avatar
joseplaselva
Posts: 60
Joined: Tue Oct 04, 2016 4:45 am

Re: Sending by mail image files from a folder

Wed Oct 18, 2017 2:00 pm

Hi, thanks again for your fast reply. I found a solution at this problem. It seems that when I declare :

Code: Select all

search_dir = "/media/pendrive"  
os.chdir(search_dir

it change the main directory, that's why it creates a new text file inside the pendrive because does not exist...
So the solution I found is to redirect again the main directory to the original path just declaring again the original path after running the read pendrive procedures :

Code: Select all

 path = "/home/pi/"
 os.chdir(path)
" "

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

Re: Sending by mail image files from a folder

Wed Oct 18, 2017 2:02 pm

There's no need to use ".close()" when using a "with" context manager structure. The close happens at the end of the block (or if there's an exception in the block).
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

User avatar
joseplaselva
Posts: 60
Joined: Tue Oct 04, 2016 4:45 am

Re: Sending by mail image files from a folder

Wed Oct 18, 2017 3:01 pm

Hereby part of the script that get mi crazy, may be you can find the error. After a loop that looks the real time to chek if the determinated stop_time has arrived, it stops capturing interval images and send those by mail.
Starts the final procediures :
1/ Send the log.txt file where are registered all the procedures of the day .
2/ Check if the pendrive folder has images files (moved when no network access)
3/ Send the images stored in the pendrive by mail and delete them.

Code: Select all

path = "/home/pi/"
moveto = "/media/pendrive/"
search_dir = "/media/pendrive"
data=""
dagtid=""
texte=""
texmed =""
netflag = 1
nrpics = 1



#----------------------------------------------------------- STARTING SHUTDOWN PROCEDURES......

            
def Shutdown():
    global nrpics
    with open('./log.txt', 'a') as log_txt:
        timenu = str(time.strftime("%H:%M:%S"))
        log_txt.write(timenu + "====================================STARTING FINAL PROCEDURES" + os.linesep)
        log_txt.write(timenu + "...CHECKING PENDRIVE..." + os.linesep)

    if nrpics ==1:
        check_pendrive()
    else:
        try:
            SendMailLog()       
        except Exception as err:
            with open('./log.txt', 'a') as log_txt:
                timenu = str(time.strftime("%H:%M:%S"))
                log_txt.write(timenu + "=!=SHUTDOWN: ERROR SENDING LOG.TXT FILE BY MAIL.......ERROR" +  os.linesep)
        turnoff()
        

def SendMailLog():

    os.chdir(path)
    with open('./log.txt', 'a') as log_txt:
        timenu = str(time.strftime("%H:%M:%S"))
        log_txt.write(timenu + "...SHUTDOWN: SENDING LOG.TXT FILE BY MAIL-" +  os.linesep)
        log_txt.write(timenu + "...TURNING RASPBERRY PI OFF IN 5 minutes  ...." +  os.linesep)
        log_txt.write(timenu + "================================== FINAL PROCEDURES ACCOMPLISHED" + os.linesep)

        
    filename = "log.txt"
    f = file(filename)
    attachment = MIMEText(f.read())
    attachment.add_header('Content-Disposition', 'attachment', filename=filename)
    
    mail = MIMEMultipart()
    mail['Subject'] = "LaSelvaPiZW-TEST-SHUTDOWN-LOG" + str(time.strftime("%y-%b-%d (%H:%M)"))
    mail['From'] = fromaddr
    mail['To'] = toaddr
    mail.attach(attachment)
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "laselva56")
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()
    
    f = open('log.txt', 'w')
    f.close()


    turnoff()
    
def check_pendrive():   
    global nrpics

    search_dir = "/media/pendrive"
    nrpics=0
    os.chdir(search_dir)
    files = filter(os.path.isfile, os.listdir(search_dir))
    files = [os.path.join(search_dir, fil) for fil in files] # add path to each file
    files.sort(key=lambda x: os.path.getmtime(x))
    for fil in files:
        nrpics = nrpics + 1


    if nrpics==0:
        try:
            SendMailLog()
        except Exception as err:
            os.chdir(path)
            with open('./log.txt', 'a') as log_txt:
                timenu = str(time.strftime("%H:%M:%S"))
                log_txt.write(timenu + "=!=SHUTDOWN: ERROR SENDING LOG.TXT BY MAIL.....ERROR" +  os.linesep)
            turnoff()
    else:
        try:
            sendmissedpics()
        except Exception as err:
            os.chdir(path)
            with open('./log.txt', 'a') as log_txt:
                timenu = str(time.strftime("%H:%M:%S"))
                log_txt.write(timenu + "=!=SHUTDOWN: ERROR SENDING MISSED PICS BY MAIL..ERROR" +  os.linesep)
            turnoff()
       

def sendmissedpics():
    global nrpics

    os.chdir(search_dir)
    files = filter(os.path.isfile, os.listdir(search_dir))
    files = [os.path.join(search_dir, fil) for fil in files] # add path to each file
    files.sort(key=lambda x: os.path.getmtime(x))
    nrpics=0
    for fil in files:
        nrpics = nrpics + 1

    print "nrpics", nrpics
    print "fil" , fil
    print "files ", files
    
    for fil in files:
        missedpic = missedpic + 1
        datum = fil[16:26]
        tid =  fil[26:32]
        timer = tid[0:3]
        minut = tid[3:6]
        jpgnam = datum + timer +":"+minut

        texte= "picture : " + jpgnam
        timenu = str(time.strftime("%A %y-%b-%d"))
        texmed = "Missed Pics " + timenu + " (pic " + str(missedpic) + "/" + str(nrpics) + ")"
        os.chdir(path)
        
        mail = MIMEMultipart()
        mail['Subject'] = str(texmed) # "Pictures from home"
        mail['From'] = fromaddr
        mail['To'] = toaddr
        mail.attach(MIMEText(texte, 'plain'))

        jpg_file=fil
        attachment = open(jpg_file, 'rb')
        image=MIMEImage(attachment.read())
        attachment.close()
        mail.attach(image)
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(fromaddr, "pasword")
        text = mail.as_string()
        server.sendmail(fromaddr, toaddr, text)
        server.quit()
        os.chdir(search_dir)
    nrpics = 0
    os.chdir(path)
    
    with open('./log.txt', 'a') as log_txt:
        timenu = str(time.strftime("%H:%M:%S"))
        log_txt.write(timenu + "...SUCCEED SENDING " + str(nrpics) +" MISSED PICS BY MAIL" +  os.linesep)
    turnoff()
 
def turnoff():

    with open('./log.txt', 'a') as log_txt:
        timenu = str(time.strftime("%H:%M:%S"))
        log_txt.write(timenu + "..TURNING OFF THE RASPBERRY IN 5 SECONDS" +  os.linesep)


    time.sleep(5) 
    os.system("sudo halt")

     
#----INTERVAL CHECKING PROCEDURES--------------------------------    

# EACH MINUTE -------------------------------------------------------------

while True:
   time_now = datetime.datetime.now().time().strftime('%H:%M:%S')
   if time_now  > stoptime:
       if netflag == 0:
            stoptime = "10:59:00"
            time.sleep(60)
       else:          
            with open('./log.txt', 'a') as log_txt:
                timenu = str(time.strftime("%H:%M:%S"))
                log_txt.write(timenu + "...STOP TIME ATTEMPTED ...." +  os.linesep)    
                  
            Shutdown()
   elif str(datetime.datetime.now().time())[6:8]== interval :
        while str(datetime.datetime.now().time())[6:8]== interval:
            time.sleep(.1)
        if time_now > startcapture:           
            capture_image()



Return to “Python”

Who is online

Users browsing this forum: Majestic-12 [Bot] and 15 guests