如果文件不存在,则发送电子邮件警报

2024-06-06 21:07:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python非常陌生

我有一个名为“etc”的文件夹,每晚生成时文件名为password.txt。我想每天在windows任务中运行一个python脚本,检查password.txt是否不存在,然后向发送电子邮件abc@ouremail.co.uk否则不要发送任何电子邮件。 我想根据以下条件触发电子邮件。当条件为“false”时,发送电子邮件,否则不采取任何操作。我如何才能做到这一点,任何帮助将不胜感激

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

亲切问候,

比斯瓦


Tags: txt脚本文件夹false文件名电子邮件windowsetc
1条回答
网友
1楼 · 发布于 2024-06-06 21:07:03

使用os.path模块检查文件是否存在

path模块为使用路径名提供了一些有用的函数。该模块可用于Python2和Python3

import os.path

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

然后,要发送电子邮件,可以使用smtplib(一个主题here

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()

相关问题 更多 >