难以在python中更新电子邮件正文

时间:2018-04-21 16:33:18

标签: python python-2.7 email ip

伙计们我是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-04-21

启动

这封邮件成功发送到tomail@domain.com,但不是一封邮件就是三个ip,它发送三封邮件与每个IP地址。请帮我通过一封邮件发送站点中列出的所有IP状态。

1 个答案:

答案 0 :(得分:0)

例如:

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)