Shell script to send email
Stefan Bogdanescu
Founder & Senior Architect
Shell Scripting Masterclass: Automating Email Notifications from Linux
As a senior developer, I often deal with scenarios where automation bridges the gap between system monitoring and human intervention. You are looking to build a self-sufficient system—a script that monitors resource usage on a remote Linux machine and automatically emails you the results when you are away. The short answer is: Yes, it is absolutely possible, and shell scripting is the perfect tool for this job.
This guide will walk you through the necessary steps, provide robust code examples, and explain the best practices for creating reliable notification scripts.
The Core Concept: Shell Scripting for System Automation
The ability to send emails from a Linux command line relies on leveraging existing Mail Transfer Agents (MTAs) installed on the system. The standard utilities used for this are typically mail, mailx, or specialized tools like sendmail. Our shell script will perform three key actions: data gathering, message construction, and transmission.
For monitoring process usage, we will use commands like ps or top to extract real-time or snapshot data, format that output into a readable body, and pipe it through an email utility.
Prerequisites and Setup
Before writing the script, ensure your Linux machine has a functional MTA installed and configured (like Postfix or Sendmail). If you are on a minimal server, you might need to install these packages first. For general system administration tasks, ensuring robust system interaction is key, much like how well-structured applications are built—reliability matters!
Step-by-Step Implementation
We will create a script that captures the CPU and memory usage of running processes and emails it directly to you.
1. Gathering Process Data
The ps command combined with filtering options is perfect for this. We can use ps aux to get a detailed list of all processes, and then filter or format the relevant columns.
2. Constructing the Email Body
The script needs to combine the gathered data with a clear header so that when you receive the email, the context is immediately clear.
3. Sending the Mail
We will use the mail command, which is universally available on most distributions for simple outbound messaging.
Starter Code Snippet
Here is a foundational snippet to get you started. This example captures the top 10 CPU-intensive processes and sends them via email.
#!/bin/bash
# --- Configuration ---
RECIPIENT="your_email@example.com"
SUBJECT="System Alert: High Process Usage Snapshot"
LOG_FILE="/tmp/process_usage_$(date +%Y%m%d).txt"
# --- Data Collection ---
echo "--- Process Usage Report ($(date)) ---" > "$LOG_FILE"
echo "Command: ps aux --sort=-%cpu | head -n 10" >> "$LOG_FILE"
echo "" >> "$LOG_FILE"
echo "Detailed process list:" >> "$LOG_FILE"
ps aux >> "$LOG_FILE"
# --- Email Sending ---
# Use the mail command to send the contents of the log file as the email body
mail -s "$SUBJECT" "$RECIPIENT" < "$LOG_FILE"
echo "Email successfully sent to $RECIPIENT."
Explanation and Best Practices
- Shebang (
#!/bin/bash): This line specifies the interpreter for the script. Always start with this. - Variables: Using variables (
RECIPIENT,SUBJECT) makes the script flexible. You can easily change the destination without editing the core logic. - Redirection (
>>and<): We use redirection to save the output to a temporary log file ($LOG_FILE) first, which keeps the email body clean and structured. Then, we pipe this content into themailcommand. - Error Handling: For production scripts, you should always add error checking (e.g., checking if the mail command succeeded) and use strict quoting to prevent unexpected behavior from special characters in filenames or email addresses.
Conclusion
Automating system monitoring via shell scripts is a powerful way to manage remote infrastructure efficiently. By mastering basic commands like ps, piping, and standard utilities like mail, you can create custom automation tools that save significant time. As you build more complex systems, remember that the principles of modularity and clear data flow—concepts central to modern development frameworks like those found in Laravel—apply perfectly here. Start simple, test thoroughly, and always prioritize security when dealing with system-level commands.
Note: Blog content is currently available in English.