Sending Custom Emails with Specific Commands on Linux: A Step-by-Step Guide

Abstract: Sends formatted custom emails from Linux scripts via Postfix and sendmail with dynamic arguments.

Created: 2026-08-28 by

To send custom emails with specific commands on Linux, configure Postfix for local delivery and use a bash script like mailSender.sh to construct the message. This approach allows you to pass arguments dynamically, ensuring that system alerts or automated reports are formatted correctly before being dispatched through your mail transfer agent.

Setting Up Postfix for Local Delivery

Before scripting email generation, you must ensure your Linux server can route messages effectively. Postfix is the standard Mail Transfer Agent (MTA) for most distributions, providing the necessary infrastructure to handle outgoing mail. For many administrative scripts, local delivery or relay to an external SMTP server is sufficient, depending on your network configuration.

Begin by installing Postfix using your distribution’s package manager. On Debian-based systems, this involves running sudo apt install postfix, while Red Hat-based systems use yum or dnf. During installation, select "Internet Site" if you intend to send mail directly to the internet, or "Satellite System" if you are relaying through another server. This initial configuration sets up the basic main.cf file, which controls how Postfix handles incoming and outgoing connections.

If your server has a dynamic IP address, you may face deliverability issues due to spam filters. In such cases, refer to guides on handling email delivery with dynamic IPs to configure proper relaying. Once installed, verify the service status with systemctl status postfix. A healthy service ensures that subsequent script executions will not fail at the transport layer.

Configuring DKIM Signatures

Modern email providers heavily filter unsigned messages. Implementing DomainKeys Identified Mail (DKIM) adds a cryptographic signature to your outgoing emails, proving their authenticity and improving inbox placement rates. To achieve this, install the opendkim package and generate a key pair associated with your domain.

Configure opendkim.conf to point to your private key and define the signing table. Then, update Postfix’s main.cf to include the milter configuration: milter_default_action = accept and milter_protocol = 2. Add the OpenDKIM socket path to smtpd_milters and non_smtpd_milters. Restart both services to apply changes. This step is crucial for any production environment where email reputation matters.

Creating the Bash Script

The core of this solution lies in a bash script that constructs the email payload. Create a file named mailSender.sh in your preferred directory, such as /usr/local/bin/. The script should accept three primary arguments: the recipient’s email address, the subject line, and the body content. Using positional parameters makes the script flexible and easy to integrate into cron jobs or other automation tools.

#!/bin/bash

RECIPIENT=$1
SUBJECT=$2
BODY=$3

# Construct the email headers and body
{
    echo "To: $RECIPIENT"
    echo "Subject: $SUBJECT"
    echo "Content-Type: text/plain; charset=UTF-8"
    echo ""
    echo "$BODY"
} | /usr/sbin/sendmail -t

This script uses the sendmail command-line interface, which is typically symlinked to Postfix on Linux systems. By piping the constructed headers and body into sendmail -t, you allow Postfix to parse the recipients and deliver the message according to its routing rules. Ensure the script is executable by running chmod +x mailSender.sh.

Passing Arguments Dynamically

When calling the script, provide the arguments in the correct order. For example, to send a system alert, you might run: ./mailSender.sh [email protected] "System Alert" "Disk usage critical". This method allows you to embed variables from other scripts, such as output from df -h or uptime, directly into the email body.

For more complex scenarios involving HTML formatting, modify the content type header to text/html and ensure the body contains valid HTML tags. However, plain text remains the most compatible format across different mail clients. If you need to debug the output, redirect the script’s stderr to a log file to capture any transmission errors.

Integrating with System Automation

Once the script is functional, integrate it into your system’s workflow. Cron jobs are ideal for scheduled reports. Edit your crontab with crontab -e and add an entry to run the script at specified intervals. For instance, to send a daily disk usage report at midnight, configure the job to execute the script with the relevant command outputs.

Additionally, consider monitoring system events. Tools like inotifywait can trigger the script when specific files change, ensuring immediate notification of important updates. This level of integration transforms a simple email sender into a robust monitoring tool. For further insights on managing user accounts without default mail directories, review resources on new user account creation without maildir structures.

Troubleshooting Common Issues

If emails do not arrive, check the Postfix mail queue using mailq. Messages stuck in the queue often indicate DNS resolution failures or authentication errors. Review the mail logs in /var/log/mail.log for detailed error messages. Common issues include incorrect SPF records, missing reverse DNS PTR records, or blocked ports by firewalls.

Ensure that your server’s hostname is fully qualified and matches the domain used in DKIM signing. Mismatched hostnames can cause rejection by recipient servers. Regularly test your setup using tools like telnet or nc to simulate SMTP transactions and verify connectivity.

Frequently Asked Questions

Can I attach files using this bash script?

Yes, but you must encode the file and construct MIME multipart boundaries manually within the script. This process is complex and error-prone, so using dedicated libraries like mpack or Python’s smtplib is often recommended for attachments.

Why are my emails going to spam?

Emails land in spam primarily due to missing or invalid DKIM, SPF, and DMARC records. Additionally, sending from a dynamic IP without proper reverse DNS configuration triggers spam filters. Ensure all authentication protocols are correctly configured.

How do I send HTML formatted emails?

Change the Content-Type header to text/html; charset=UTF-8 in your script. Ensure the body content includes valid HTML tags and is properly escaped to prevent injection attacks or rendering issues in various mail clients.

Is it safe to store passwords in the script?

No, never hardcode credentials in executable scripts. Use environment variables or secure credential managers. If using an external SMTP relay, configure authentication in Postfix’s main.cf or use SASL mechanisms rather than passing passwords via command-line arguments.

What if Postfix is not installed?

You can use alternative MTAs like Sendmail or Exim, or rely on command-line tools like mutt or heirloom-mailx. However, Postfix is generally preferred for its stability and extensive documentation in Linux environments.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More