Trying to create a piece of python code that monitors a directory for new randomly named csv files. For some reason I cannot find a way to use the unix trick of *.cvs to work. and then i need to have to particular file to be emailed and moved to a different directory. this is my code so far
#!/usr/bin/env python
import os
import base64
import smtplib
import mimetypes
import email
import email.mime.application
import shutil
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
#locate file and send it to the email
for file in os.listdir("/root/tmp/"):
if file.endswith(".csv"):
fromaddr = "FROM EMAIL"
toaddr = "TO EMAIL"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "CSV"
body = "CSV SENT SUCCESSFULLY"
msg.attach(MIMEText(body, 'plain'))
filename = "prod.csv" # <-- trying to keep the file name from below as it finds it
attachment = open("/root/tmp/prod.csv", "rb") # <--- need to send cvs as they come in
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 ADDRESS', 587)
server.starttls()
server.login(fromaddr, "PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
#move to a different folder once sent
path = "/root/tmp/" # <--- using root for testing :)
moveto = "/root/sent/" # <-- destination folder
files = os.listdir(path)
files.sort()
for f in files:
src = path+f
dst = moveto+f
shutil.move(src,dst)
Aucun commentaire:
Enregistrer un commentaire