How to create a script to mail from unix
To create a script to mail from a Unix system, you can use the mail
command or the sendmail
command. Here are some examples:
Using the mail
command:
- Create a new file with a
.sh
extension (e.g.,mail_script.sh
) and add the following content:#!/bin/bash
Set the recipient's email address
TO_EMAIL="[email protected]"
Set the subject of the email
SUBJECT="Test email from Unix script"
Set the body of the email
BODY="This is a test email sent from a Unix script."
Use the mail command to send the email
mail -s "$SUBJECT" "$TO_EMAIL" << EOF $BODY EOF
2. Make the script executable by running the command `chmod +x mail_script.sh`.
3. Run the script by typing `./mail_script.sh`.
**Using the `sendmail` command:**
1. Create a new file with a `.sh` extension (e.g., `sendmail_script.sh`) and add the following content:
```bash
#!/bin/bash
# Set the recipient's email address
TO_EMAIL="[email protected]"
# Set the subject of the email
SUBJECT="Test email from Unix script"
# Set the body of the email
BODY="This is a test email sent from a Unix script."
# Use the sendmail command to send the email
sendmail -v -t << EOF
To: $TO_EMAIL
Subject: $SUBJECT
$BODY
EOF
- Make the script executable by running the command
chmod +x sendmail_script.sh
. - Run the script by typing
./sendmail_script.sh
.
Tips and Variations:
- You can customize the script to include additional headers, such as
From
orCC
. - You can use variables to store the recipient's email address, subject, and body, and then use those variables in the
mail
orsendmail
command. - You can use the
mail
command with the-a
option to attach a file to the email. - You can use the
sendmail
command with the-f
option to specify the sender's email address. - You can use the
mail
orsendmail
command with the-v
option to enable verbose mode, which can be helpful for debugging purposes.
Remember to replace the [email protected]
email address with the actual email address you want to send the email to.