Friday, April 3, 2026

Linux sendmail utility to send attachment

12:48 PM Posted by Dilli Raj Maharjan No comments

     In Linux, sendmail is an inbuilt utility command used in scripts for system-generated notifications. It is also a powerful Mail Transfer Agent (MTA). There are a lot of email utilities like mailx, mail, mutt, and others, but some clients prefer not to install those utilities as part of the security requirements. Sending a simple email with the sendmail utility is easier, but attaching a file to the email is a little bit tricky. Here is the script you can use to send an email with an attachment using the sendmail utility.

Sending an email with an attachment using the sendmail utility.

#!/bin/bash

# Define variables. Replace with the required values.
FROM="noreply@dilli.com.np"
TO="someone@dilli.com.np"
SUBJECT="Sales report for the month of March 2026"
ATTACHMENT="/home/dillimaharjan/sales_2026_03.xls"
FILENAME=$(basename "$ATTACHMENT")
BOUNDARY="zKz_Stm68rdgV3UqG_u_njPvGH"
# Create headers and the email body as required. ( echo "From: $FROM" echo "To: $TO" echo "Subject: $SUBJECT" echo "MIME-Version: 1.0" echo "Content-Type: multipart/mixed; boundary=\"$BOUNDARY\"" echo "" echo "--$BOUNDARY" echo "Content-Type: text/plain; charset=US-ASCII" echo "Content-Transfer-Encoding: 7bit" echo "" echo "Dear sir,
Attach is the sales report for the month of March 2026.

Thank you,
Dilli Raj Maharjan."
echo "" # Add the attachment echo "--$BOUNDARY" echo "Content-Type: application/octet-stream; name=\"$FILENAME\"" echo "Content-Transfer-Encoding: base64" echo "Content-Disposition: attachment; filename=\"$FILENAME\"" echo "" # Encode the attachment using base64 base64 "$ATTACHMENT" echo "" # End the email echo "--$BOUNDARY--" ) | sendmail -t

Sending an email with HTML contents using the sendmail utility.

#!/bin/bash

# --- Configuration ---
TO="noreply@dilli.com.np"
FROM="someone@dilli.com.np"
SUBJECT="Sales report for month of March 2026" HTML_FILE="/path/to/your/content.html" # Your HTML content is in this file # --- Logic --- ( echo "From: $FROM" echo "To: $TO" echo "Subject: $SUBJECT" echo "MIME-Version: 1.0" echo "Content-Type: text/html; charset=UTF-8" # This line is crucial echo "" # An empty line separates headers from the body
  echo "Dear sir,
Here is the sales report for the Month of March 2026. "
  cat "$HTML_FILE" # Add the HTML content from your file
  echo "Regards,
  Dilli Maharjan"
) | sendmail -t