简体   繁体   English

Email 如果文件不存在则发出警报 - Python

[英]Email alert if file doesn't exist - Python

I'm very new to python.我对 python 很陌生。

I have a folder called "etc" with a filename password.txt when generates every night.每天晚上生成时,我有一个名为“etc”的文件夹,其文件名为 password.txt。 I would like to run a python script in windows task on daily basis to check if password.txt doesn't exist then send email to abc@ouremail.co.uk else do not send any email. I would like to run a python script in windows task on daily basis to check if password.txt doesn't exist then send email to abc@ouremail.co.uk else do not send any email. I want to trigger email based on the below condition.我想根据以下条件触发 email。 When the condition is "false" send email else no action taken.当条件为“假”时,发送 email 否则不采取任何措施。 How can I achieve it, any help on this would be greatly appreciated.我该如何实现它,对此的任何帮助将不胜感激。

os.path.isfile("/etc/password.txt") True os.path.isfile("/etc/password.txt") True

Kind regards,亲切的问候,

Biswa比斯瓦

Check if File Exists using the os.path Module使用 os.path 模块检查文件是否存在

The os.path module provides some useful functions for working with pathnames. os.path 模块提供了一些有用的函数来处理路径名。 The module is available for both Python 2 and 3该模块适用于 Python 2 和 3

import os.path

if os.path.isfile('filename.txt'):
    print ("File exist")
else:
    print ("File not exist")

Then to send an email you can use smtplib (one topic here )然后发送 email 您可以使用 smtplib( 这里有一个主题)

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

msg = MIMEMultipart()
msg['From'] = 'me@gmail.com'
msg['To'] = 'you@gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))

mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('me@gmail.com', 'mypassword')

mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string())

mailserver.quit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM