#!/bin/bash
# Script Name: sendmail_test.sh
# Version: 03
# Description: This script sends a test email using sendmail. The recipient's email address is the first argument.
#              It logs messages to the console only.

# Check if an argument (email address) is provided
if [ -z "$1" ]; then
    TO="root"
else
    TO="$1"
fi

# Email details
SUBJECT="Postfix Test"
FROM="$(whoami)@$(hostname)"
BODY="This is the email body!"

# Function to send email
send_email() {
    if ! command -v sendmail &> /dev/null; then
        echo "Sendmail is not installed or configured. Please ensure sendmail is installed and properly set up." >&2
        exit 1
    fi

    sendmail -t <<EOF
To: $TO
Subject: $SUBJECT
From: $FROM

$BODY
EOF
}

# Function to log messages
log_message() {
    MESSAGE=$1
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $MESSAGE"
}

# Send email and log the result
log_message "Starting email send process."
if send_email; then
    log_message "Email sent successfully to $TO."
else
    log_message "Failed to send email to $TO."
fi