Debug School

rakesh kumar
rakesh kumar

Posted on

How to send email using bash script

This script is a Bash script used to send an email via SMTP using the sendemail command-line utility. It connects to an SMTP server (Amazon SES in this case) to send an email.

Image description

Image description

Check if sendemail is Installed

if ! command -v sendemail &> /dev/null
then
    echo "Error: sendemail is not installed. Install it using 'sudo apt-get install sendemail'."
    exit 1
fi
Enter fullscreen mode Exit fullscreen mode

This checks if the sendemail command is available.
If sendemail is not installed, it prints an error message and exits.
You can install it using:

sudo apt-get install sendemail
Enter fullscreen mode Exit fullscreen mode
  1. S*end the Email using sendemail*
sendemail \
    -f "$FROM_EMAIL" \
    -t "$TO_EMAIL" \
    -u "$SUBJECT" \
    -m "$BODY" \
    -s "$SMTP_SERVER:$SMTP_PORT" \
    -xu "$SMTP_USER" \
    -xp "$SMTP_PASS" \
    -o tls=yes
sendemail is used to send the email with the configured SMTP server.
-f "$FROM_EMAIL" → Sets the sender's email.
-t "$TO_EMAIL" → Sets the recipient's email.
-u "$SUBJECT" → Sets the email subject.
-m "$BODY" → Sets the email body/message.
-s "$SMTP_SERVER:$SMTP_PORT" → Configures SMTP server and port.
-xu "$SMTP_USER" → Sets the SMTP username.
-xp "$SMTP_PASS" → Sets the SMTP password.
Enter fullscreen mode Exit fullscreen mode

-o tls=yes → Enables TLS encryption for secure communication.

  1. Check if Email Was Sent Successfully
if [ $? -eq 0 ]; then
    echo "Email sent successfully to $TO_EMAIL."
else
    echo "Failed to send the email. Check SMTP credentials or connection."
fi
Enter fullscreen mode Exit fullscreen mode

$? stores the exit status of the previous command.
If the exit status is 0, the email was sent successfully.
Otherwise, it prints an error message (e.g., invalid credentials, network issues).
How to Run the Script?
Save the script to a file, e.g., send_email.sh.
Give execution permissions:

chmod +x send_email.sh
Enter fullscreen mode Exit fullscreen mode

Run the script:

./send_email.sh
Enter fullscreen mode Exit fullscreen mode

FULL CODE

Image description

Top comments (0)