Automating Report Distribution: A Python Script for Emailing Missing Files
--
Listen
Share
In today’s fast-paced business environment, the timely distribution of reports is critical. Automating this process can save significant time and reduce errors. In this blog post, we’ll explore a Python script designed to automate the task of finding and emailing missing report files to a specified list of recipients. We’ll dive into each function of the script and explain how it works, along with the expected output.
Overview of the Script
This Python script is designed to run on specific servers, check for missing report files from the previous days, and email these files to a predefined list of recipients. The script is broken down into several key functions, each responsible for a specific part of the process:
- Import necessary modules
- Clear the Screen
- Get Server Information
- Determine Days Back
- Change Directory
- Find Files
- Send Email
- Main Function
Let’s explore each function in detail.
- Import necessary modules some constant dictonary key as Server_tag_map(): and server_arg_map():
see some samples:
mport datetimeimport osimport smtplibimport socketimport sysfrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText# Dictionary of servers and their corresponding TAG valuesserver_tag_map = { 'MYSERVER1': 'FIN', 'MYSERVER2': 'TEC', 'MYSERVER3': 'POS'}# Dictionary of servers and their corresponding argument valuesserver_arg_map = { 'MYSERVER1': 111111, 'MYSERVER2': 222222, 'MYSERVER3': 333333}
- Clear the Screen
def clear_screen(): if os.name == 'posix': # For Linux and macOS os.system('clear') elif os.name == 'nt': # For Windows os.system('cls')
Purpose: This function clears the terminal screen for better readability when the script runs. It detects the operating system and executes the appropriate command to clear the screen.
Expected Output: The terminal screen will be cleared.
- Get Server Information
def get_server_info(): server_name = socket.gethostname().upper() if server_name not in server_tag_map: print("\n[+] Please run this script from one of the following servers: NAMDLPDIMDCSW82, NAMDLPENFSW02, NAMDLPDIMECSW91.") sys.exit(1) return server_name, server_arg_map[server_name], server_tag_map[server_name]
Purpose: This function retrieves the server’s hostname, checks if it’s one of the predefined servers, and returns the server name, corresponding argument value, and tag value.
Expected Output: The function will return server-specific information or exit if the server is not recognized.
- Determine Days Back
def get_days_back(): days_back = 1 # Default to 1 day back (yesterday) if len(sys.argv) >= 2: days_back = int(sys.argv[1]) if days_back < 1: print("\n[+] Days back value must be at least 1.") sys.exit(1) return days_back
Purpose: This function determines how many days back the script should look for the missing files. By default, it looks one day back, but this can be overridden by providing an argument when running the script.
Expected Output: The number of days back to check for files.
- Change Directory
def change_directory(): os.chdir("/opt/reports")
Purpose: This function changes the current working directory to the specified path where the reports are stored.
Expected Output: The working directory will be changed to /opt/reports.
- Find Files
def find_files(arg_value, days_back): found_files = [] for day in range(days_back): target_date = datetime.date.today() - datetime.timedelta(days=day) print("\n[+] Checking for date [{}]\n".format(target_date)) file_pattern = "NAME_PROD_{}_{}.txt".format(arg_value, target_date.strftime("%Y-%m-%d")) print("\n[+] File Pattern is [{}]\n".format(file_pattern)) for filename in os.listdir("."): if file_pattern in filename: found_files.append(filename) break return found_files
Purpose: This function looks for files matching a specific pattern based on the argument value and target dates. It checks for each day within the specified range and returns a list of found files.
Expected Output: A list of filenames that match the pattern.
- Send Email
def send_email(filenames, recipients): hostname = socket.gethostname() sender = "pro_user@{}".format(hostname) if isinstance(recipients, str): receivers = recipients.split(',') receivers = [email.strip() for email in receivers] else: receivers = recipients msg = MIMEMultipart() current_date = datetime.date.today().strftime("%Y-%m-%d") msg["Subject"] = "Here are the missing files attached on {}".format(current_date) msg["From"] = sender msg["To"] = ", ".join(receivers) body = "Hi team,\n\nHere is/are the missing files:\n" for i, filename in enumerate(filenames, start=1): body += "{}. {}\n".format(i, filename) body += "\nThanks.\n\nOPS Team." msg.attach(MIMEText(body, 'plain')) for filename in filenames: with open(filename, "rb") as f: attachment = MIMEApplication(f.read(), _subtype="txt") attachment.add_header("Content-Disposition", "attachment", filename=filename) msg.attach(attachment) smtp = smtplib.SMTP("localhost") smtp.sendmail(sender, receivers, msg.as_string()) smtp.quit() print("\n[+] Files have been emailed to the recipients:\n {}\n\n".format(", ".join(receivers)))
Purpose: This function sends an email with the found files attached to the specified recipients. It constructs an email message, attaches the files, and sends the email using the local SMTP server.
Expected Output: An email will be sent to the recipients with the missing files attached, and a confirmation message will be printed.
- Main Function
def main(): clear_screen() server_name, arg_value, tag_value = get_server_info() days_back = get_days_back() change_directory() found_files = find_files(arg_value, days_back) if found_files: print("\n[+] Files matched and found: {}\n".format(", ".join(found_files))) # Single recipient # do = "[email protected]" # send_email(found_files, do) # Multiple recipients do = "[email protected], [email protected]" send_email(found_files, do) else: print("\n[-] No files found matching the pattern NAME_PROD_{}.txt with the argument value {}.".format( datetime.date.today().strftime("%Y-%m-%d"), arg_value))if __name__ == "__main__": main()
Purpose: The main function orchestrates the execution of all other functions. It clears the screen, retrieves server information, determines the number of days back, changes the working directory, finds the files, and sends an email with the found files attached.
Expected Output: The script will run through all the steps and either email the found files to the specified recipients or indicate that no files were found.
Conclusion
This Python script provides a robust solution for automating the process of finding and emailing missing report files. By breaking down the task into clear, manageable functions, it ensures each step is handled efficiently and transparently. Whether you need to check for missing files from the previous day or from a range of days, this script can be easily adapted to meet your needs. Happy automating!
Top comments (0)