Bash script send mail

Here is an example of a bash script that sends an email using the mail command:

#!/bin/bash

# Set the recipient's email address
RECIPIENT="[email protected]"

# Set the subject of the email
SUBJECT="Test email from bash script"

# Set the body of the email
BODY="This is a test email sent from a bash script."

# Use the mail command to send the email
echo "To: $RECIPIENT" | mail -s "$SUBJECT" $RECIPIENT

Let me explain what each line does:

  1. #!/bin/bash: This line specifies the interpreter that should be used to run the script. In this case, it's bash.
  2. RECIPIENT="[email protected]": This line sets the recipient's email address to [email protected].
  3. SUBJECT="Test email from bash script": This line sets the subject of the email to Test email from bash script.
  4. BODY="This is a test email sent from a bash script.": This line sets the body of the email to This is a test email sent from a bash script..
  5. echo "To: $RECIPIENT" | mail -s "$SUBJECT" $RECIPIENT: This line uses the echo command to print the email headers (including the recipient's address) and the mail command to send the email. The -s option specifies the subject of the email, and the $RECIPIENT variable is used to specify the recipient's email address.

To use this script, save it to a file (e.g., send_email.sh), make the file executable with chmod +x send_email.sh, and then run it with ./send_email.sh.

Alternatively, you can use the sendmail command instead of mail. Here is an example:

#!/bin/bash

# Set the recipient's email address
RECIPIENT="[email protected]"

# Set the subject of the email
SUBJECT="Test email from bash script"

# Set the body of the email
BODY="This is a test email sent from a bash script."

# Use the sendmail command to send the email
sendmail -v -f $RECIPIENT -s "$SUBJECT" <<EOF
$BODY
EOF

This script uses the sendmail command to send the email, and the <<EOF syntax to specify the email body. The -v option enables verbose mode, which can be helpful for debugging.