Python Forum
Send Email Based on Condition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Send Email Based on Condition
#1
Hi All,

I have the following code which sends an email when Linux partitions reach a certain threshold:

from email.headerregistry import Address
from email.message import EmailMessage
from email.mime.text import MIMEText
import os
import smtplib
import psutil

# mail server details
mail_server = 'localhost'
mail_server_port = 25

# OS variables
email_address = os.getenv('MAIL_ADDRESS', None)
recipient_address = os.getenv('TO_ADDR', None)
host = os.getenv('HOST', None)
limit = os.getenv('LIMIT', None)

# linux mount points
#
# cast string to integer object with int() function
#
def mounts():
    devs = psutil.disk_partitions()
    for dev in devs:
            part = int(psutil.disk_usage(dev.mountpoint).percent)
            if part > int(limit):
                yield [dev.mountpoint, part]

# converting objects returned from mount() function to a list
list_mounts = list(mounts())

# format list
def list_out(list_in):
    return '\n'.join('Drive: {0:10s} Used Space: {1:5.2f}'.format(*drive) for drive in list_in)

# assign list output to variable for email body
email_body = list_out(list_mounts)
email_string = '''
Please check the following drive(s):
{drive_lines}
'''.format(drive_lines=email_body)

# email function
def create_email_message(from_address, to_address, subject, body):
        msg = EmailMessage()
        msg['From'] = from_address
        msg['To'] = to_address
        msg['Subject'] = subject
        msg.set_content(body)
        return msg

# main function
if __name__ == '__main__':
        msg = create_email_message(
                from_address=email_address,
                to_address=recipient_address,
                subject='Warning - Drive Space Usage - {}'.format(host),
                body=email_string
        )

with smtplib.SMTP(mail_server, mail_server_port) as smtp_server:
        smtp_server.ehlo()
        smtp_server.send_message(msg)
My ultimate plan is to use this code to monitor storage thresholds on a Linux. When a mount point reaches say 75% usage, I want the email to be sent. I'll be scheduling a cron job to run the script every 5 minutes. In it's current state, an email will be sent every 5 minutes no matter the threshold limit.

I was planning on using a simple conditional statement counting the value of the list_mounts variable. However, my placement of the condition hasn't been fruitful.

if len(list_mounts) > 0:
# main function
        if __name__ == '__main__':
                msg = create_email_message(
                        from_address=email_address,
                        to_address=recipient_address,
                        subject='Warning - Drive Space Usage - {}'.format(host),
                        body=email_string
                )
Any ideas where I could place this statement or am I going down the wrong road?

Thanks!
Reply
#2
what about this:

from email.headerregistry import Address
from email.message import EmailMessage
from email.mime.text import MIMEText
import os
import smtplib
import psutil
  
# mail server details
mail_server = 'localhost'
mail_server_port = 25
  
# OS variables
email_address = os.getenv('MAIL_ADDRESS', None)
recipient_address = os.getenv('TO_ADDR', None)
host = os.getenv('HOST', None)
limit = os.getenv('LIMIT', None)
  
# linux mount points
# cast string to integer object with int() function
def mounts():
    devs = psutil.disk_partitions()
    for dev in devs:
        part = int(psutil.disk_usage(dev.mountpoint).percent)
        if part > int(limit):
            yield [dev.mountpoint, part]
  
 
# format list
def list_out(list_in):
    return '\n'.join('Drive: {0:10s} Used Space: {1:5.2f}'.format(*drive) for drive in list_in)
 
# email function
def create_email_message(from_address, to_address, subject, body):
    msg = EmailMessage()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = subject
    msg.set_content(body)
    return msg
  
if __name__ == '__main__':
    # converting objects returned from mount() function to a list
    list_mounts = list(mounts())
     
    if list_mounts:
        # assign list output to variable for email body
        email_body = list_out(list_mounts)
        email_string = '''
        Please check the following drive(s):
        {drive_lines}
        '''.format(drive_lines=email_body)
        msg = create_email_message(
                from_address=email_address,
                to_address=recipient_address,
                subject='Warning - Drive Space Usage - {}'.format(host),
                body=email_string)
      
        with smtplib.SMTP(mail_server, mail_server_port) as smtp_server:
            smtp_server.ehlo()
            smtp_server.send_message(msg)
Also I would pass some arguments to mount function instead of using global variables like limit
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
That worked, thx! The output of the email is a bit off so I'm looking into that now. Also, I'm going to pass some arguments to their respective functions. Once I work on the formatting of the output I'll post the final code.

Output:
Please check the following drive(s): Drive: /boot Used Space: 46.00 Drive: /home Used Space: 52.00 Drive: /usr Used Space: 44.00 Drive: /var Used Space: 46.00 Drive: /u01 Used Space: 61.00 Drive: /backups Used Space: 69.00

The latest:

Output:
Please check the following drive(s): Drive: /boot Used Space: 46.00 Drive: /home Used Space: 52.00 Drive: /usr Used Space: 44.00
I add the lstrip() function to the end of the 'body' argument:

        if list_mounts:
                # create email message content
                msg = create_email_message(
                        from_address=email_address,
                        to_address=recipient_address,
                        subject='Warning - Drive Space Usage - {}'.format(host),
                        body=email_string.lstrip())
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 457 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Sent email based on if condition stewietopg 1 869 Mar-15-2023, 08:54 AM
Last Post: menator01
  Send email with smtp without using Mimetext mgallotti 0 717 Feb-01-2023, 04:43 AM
Last Post: mgallotti
  create new column based on condition arvin 12 2,255 Dec-13-2022, 04:53 PM
Last Post: jefsummers
  email Library: properly send message as quoted-printable malonn 3 1,342 Nov-14-2022, 09:31 PM
Last Post: malonn
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 849 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 1,532 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Unable to send email attachments cosmarchy 7 2,589 Mar-09-2022, 09:29 PM
Last Post: bowlofred
  How to make scraper send email notification just once themech25 0 1,392 Nov-08-2021, 01:51 PM
Last Post: themech25
  How to map two data frames based on multiple condition SriRajesh 0 1,494 Oct-27-2021, 02:43 PM
Last Post: SriRajesh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020