Python Forum
Sent email based on if condition - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sent email based on if condition (/thread-39606.html)



Sent email based on if condition - stewietopg - Mar-15-2023

I have script which reads device info from database - IP, LOCATION and STATUS

First it checks if device has status "ACTIVE" if yes than it pings device (incase of any technical problems)

if ping is successful it stores IP of device to list
if ping is unsuccessful than it sends me email

I would like to ask how to send all unresponsive devices in one email? Now i get separate email for each device.

My current code:
# email

def email(ip, location):
    fromaddr = "@gmail.com"
    toaddr = "@gmail.com"
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "Unresponsive device"
    body = """<html><head></head>""" + "IP: " + ip + "<br>" + "Location: " + location+ "</html>"
    msg.attach(MIMEText(body, 'html'))
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "XXXXX")
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

# ping

def ping(host):
    result = os.popen(' '.join(("ping", ping.param, host))).read()
    return 'ttl=' in result.lower()

ping.param = "-n 1" if platform.system().lower() == "windows" else "-c 1"

# get devices

mycursor.execute("SELECT ip, location, status FROM devices")
devices = mycursor.fetchall()

ips = []

for device in devices:
    active = device[2]
    if active == "ACTIVE":
        a = ping(device[0])
        if a == True:
            ip = device[0]
            ips.append(ip)
        else:
            email(device[0], device[1])



RE: Sent email based on if condition - menator01 - Mar-15-2023

You could add it to a list, then send the list after all devices are appended.