问题
I would like to script a function wich is looking in a particular directory for files, if there are new files, it should send out an notification email.
I already prepared a script which is looking for new files in a directory, it write the notification about a new file into the console. But now I would like to notified via email, as soon as there has a new file arrived. Could someone help?
import os, time
def run():
path_to_watch = "//D$:/testfolder/"
print "watching: " + path_to_watch
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
after = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if added: print "Added: ", ", ".join (added)
if removed: print "Removed: ", ", ".join (removed)
before = after
time.sleep (10)
if __name__ == "__main__":
print run()
回答1:
It's very simple if you have an SMTP mail server set up (i'm assuming you have a mail system!). Will take you about 10 lines of code in total. Here is a python example.
If you have any problems, we will need more information to help further. For example, what mail system you are using e.t.c.
回答2:
OKI, in this case I have worked out my own solution. Probably it can help somebody with a similar task to resolve.
import os, time, smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
path_to_watch = "//networkpath/test/filetest"
print "watching: " + path_to_watch
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
after = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if removed: print "Removed: ", ", ".join (removed)
if added:
print "Added: ", ", ".join (added)
me = "me@test.de"
you = "you@test.de"
msg = MIMEMultipart('alternative')
msg['Subject'] = "New file has approached."
msg['From'] = me
msg['To'] = you
text = "New file has approached in:\n\\\networkpath\test\filetest"
part1 = MIMEText(text, 'plain')
msg.attach(part1)
s = smtplib.SMTP('smtp.test.com')
s.sendmail(me, you, msg.as_string())
s.quit()
time.sleep (10)
before = after
Have fun!
来源:https://stackoverflow.com/questions/3987134/email-notification-on-file-change-in-particular-directory-with-python