如果值符合某个条件,我写了一个脚本来发送电子邮件。我想在每次检查时发送1封电子邮件而不是多封电子邮件。我认为我可以通过投入另一个功能来缓解但我无法弄清楚如何去做。关于如何实现这一目标的任何想法?
import csv, requests, xmltodict, smtplib, email.utils
from email.mime.text import MIMEText
def sendEmail(host, value, devicename):
# Create the message
msg = MIMEText('This is the body of the message.')
msg['To'] = email.utils.formataddr(('Recipient', 'XXXXXX'))
msg['From'] = email.utils.formataddr(('Author', 'XXXXX'))
msg['Subject'] = 'Simple test message'
server = smtplib.SMTP('XXXXXXX')
server.set_debuglevel(True) # show communication with the server
try:
server.sendmail('XXXXXX', ['XXXXXX'], msg.as_string())
finally:
server.quit()
def check(hostIP, value):
xml = """<?xml version="1.0" encoding="iso-8859-1"?>"""
headers = {'Content-Type': 'application/xml'}
response = requests.post('http://' + hostIP + '/RPC2', data=xml, headers=headers).text
doc = xmltodict.parse(response)
uptime = str(doc['response'])
maxtime = '300'
time = str(uptimeValue)
day = time // (24 * 3600)
if day >= maxtime:
print 'it is'
sendEmail(str(hostIP), str(value), str(devicename))
else:
print "it is not!"
def main():
try:
with open('list.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
check(row['Host'], row['Value'])
except Exception as error:
print ValueError("Could not properly read the csv file")
sys.exit(0)
if __name__ == "__main__":
main()
答案 0 :(得分:1)
替换
def sendEmail(message):
和
if day >= maxtime:
print 'it is'
return (str(hostIP), str(value), str(devicename))
和
device_list = []
for row in reader:
result = check(row['Host'], row['Value'])
if result:
device_list.append(', '.join(result))
sendEmail('\n'.join(device_list))
答案 1 :(得分:0)
不使用check
发送电子邮件,而是使用它来添加项目以进入邮件正文,可能是在数组或字典中。然后,在处理完文件后,您可以使用收集到的信息构建电子邮件正文,只需拨打sendEmail
一次。
这意味着您不能从sendEmail
内部拨打check
;完成文件后,您可以从main
调用它。