Linux mail attach file script

Here is an example of a Linux script that sends an email with an attached file:

#!/bin/bash

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

# Set the subject of the email
SUBJECT="Example Email with Attachment"

# Set the file to attach
FILE="example.txt"

# Set the email body
BODY="This is an example email with an attachment."

# Use the `mail` command to send the email
echo "To: $RECIPIENT" | mail -s "$SUBJECT" -a "$FILE" -b "$BODY"

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.
  3. SUBJECT="Example Email with Attachment": This line sets the subject of the email.
  4. FILE="example.txt": This line sets the file to attach.
  5. BODY="This is an example email with an attachment.": This line sets the email body.
  6. echo "To: $RECIPIENT" | mail -s "$SUBJECT" -a "$FILE" -b "$BODY": This line uses the mail command to send the email. The options used are:
    • -s specifies the subject of the email.
    • -a specifies the file to attach.
    • -b specifies the email body.

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.

Note: This script uses the mail command, which is a simple email client that is included with many Linux distributions. If you want to use a more advanced email client, you may need to use a different command or script.

Also, you can use mutt command instead of mail command, it's more powerful and flexible.

echo "To: $RECIPIENT" | mutt -s "$SUBJECT" -a "$FILE" -b "$BODY"

You can also use sendmail command, it's a more advanced email client that allows you to specify the sender's email address, the recipient's email address, and the email body.

sendmail -v -f "[email protected]" -t -i -a "$FILE" -b "$BODY" $RECIPIENT

Make sure to replace [email protected] with your actual email address.