[英]Difficulty updating e-mail body in python
伙计们,我是python的新手,但是我在各种网站及其工作的帮助下制作了以下代码,但问题是它为站点列表中的每个IP地址发送了单独的邮件。 帮助我构造具有所有IP地址的邮件正文。
ping.py
#!/usr/bin/env python
import smtplib
import pyping
from conf import settings, sites
import time
import datetime
"""Sends an e-mail to the specified recipient."""
sender = settings["monitor_email"]
recipient = settings["recipient_email"]
subject = settings["email_subject"]
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(settings["monitor_server"], settings["monitor_server_port"])
session.ehlo()
session.login(settings["monitor_email"], settings["monitor_password"])
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
for site in sites:
checker = pyping.ping(site)
# The site status changed from it's last value, so send an email
if checker.ret_code == 0:
# The site is UP
body = "%s This Server is up %s" % (site, st)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
else:
# The site is Down
body = "%s This Server is down %s" % (site, st)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
这是我的conf.py
sites = (
"192.168.1.1",
"192.168.2.1",
"192.168.3.1",
)
settings = {
"recipient_email": 'tomail@domain.com',
"monitor_email": 'frommail@domain.com',
"monitor_password": 'password',
# Leave as it is to use gmail as the server
"monitor_server": 'frommail@domain.com',
"monitor_server_port": 587,
# Optional Settings
"email_subject": 'Server Monitor Alert'
}
我得到的输出为:
服务器监视器警报
192.168.1.1该服务器于2018年4月21日启动
该邮件成功发送到tomail@domain.com,但没有以单个邮件发送三个ip,而是以每个IP地址发送三个邮件。 请帮助我在一封邮件中发送站点中列出的所有IP状态。
例如:
temp = []
for site in sites:
checker = pyping.ping(site)
# The site status changed from it's last value, so send an email
if checker.ret_code == 0:
# The site is UP
body = "%s This Server is up %s" % (site, st)
temp.append(body)
else:
# The site is Down
body = "%s This Server is down %s" % (site, st)
temp.append(body)
body = '\n'.join(temp)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.