Using mutt to Send HTML Emails with Attachments
Basic Command Usage
The basic mutt
command for sending HTML emails with attachments follows this pattern:
mutt -e 'set content_type="text/html"' -s "Subject" recipient@domain.com -a /path/to/attachment < /path/to/html_message
Let’s break down each component:
-e 'set content_type="text/html"'
: Tells mutt to send the email as HTML-s "Subject"
: Sets the email subjectrecipient@domain.com
: The email recipient-a /path/to/attachment
: Specifies the file to attach< /path/to/html_message
: The HTML content of your email
Script Implementation
Here’s a general implementation that can be used for any backup or sync operation:
#!/bin/bash
# Configuration
MAIL_TO="admin@yourdomain.com"
LOG_FILE="/path/to/your/logfile.log"
MAIL_BODY="/tmp/notification.html"
# Your sync/backup command here
your_command
STATUS=$? # Capture the exit status of your command
# Determine status based on command result
if [ $STATUS -eq 0 ]; then
BACKUP_STATUS="SUCCESS"
else
BACKUP_STATUS="FAILED"
fi
# Create HTML email content
cat > $MAIL_BODY << EOF
<html>
<body>
<h2>Operation Report</h2>
<p>Status: <strong>${BACKUP_STATUS}</strong></p>
<p>See attached log file for details.</p>
</body>
</html>
EOF
# Function to send the email
function send_mail {
local subject="Operation finished with ${BACKUP_STATUS}"
if [ ! -f "$LOG_FILE" ]; then
echo "Error: Log file not found"
return 1
}
mutt -e 'set content_type="text/html"' \
-s "$subject" \
"$MAIL_TO" \
-a "$LOG_FILE" < "$MAIL_BODY"
local mail_status=$?
rm -f "$MAIL_BODY" # Clean up temporary file
return $mail_status
}
# Send the email and capture the result
send_mail
if [ $? -eq 0 ]; then
echo "Email notification sent successfully"
else
echo "Failed to send email notification"
exit 1
fi
Usage Example
Here’s how you might use this in practice:
# Example with rsync
rsync -av source/ destination/ > "$LOG_FILE" 2>&1
STATUS=$?
# Or with any other command that returns a status
your_backup_command > "$LOG_FILE" 2>&1
STATUS=$?
Tips
- Always capture the exit status of your command using
$?
- Use descriptive subject lines that include the status
- Clean up temporary files after sending
- Quote your variables to handle spaces and special characters
- Add appropriate error checking for files and commands
This template can be adapted for any operation where you need to send an HTML email notification with an attached log file, based on the success or failure of a command.