To use the mail
command in a shell script, you can use the mail
command followed by the options and arguments that you want to use.
Here is an example of a shell script that uses the mail
command to send an email:
# Set the recipient and subject recipient=user@example.com subject="Hello from the shell" # Set the body of the email body="This is an email sent from the shell" # Send the email echo "$body" | mail -s "$subject" "$recipient"
This script sets the recipient, subject, and body of the email, and then sends the email using the mail
command. The -s
option specifies the subject of the email, and the echo "$body"
command pipes the body of the email to the mail
command.
You can use other options with the mail
command to customize the email. For example, you can use the -a
option to attach a file to the email, or the -c
option to specify a carbon copy recipient.
Here is an example of a shell script that uses the mail
command to send an email with an attachment:
# Set the recipient, subject, and attachment recipient=user@example.com subject="Hello from the shell" attachment=/path/to/attachment.txt # Set the body of the email body="This is an email sent from the shell" # Send the email with the attachment echo "$body" | mail -s "$subject" -a "$attachment" "$recipient"
This script attaches the file /path/to/attachment.txt
to the email, and sends it to the recipient user@example.com
with the subject "Hello from the shell".
For more information about the mail
command and its options, you can consult the mail
man page by running the man mail
command.
Keep in mind that the mail
command is not available on all Unix and Linux systems, and it may have different options and behavior depending on the system and the mail server that you are using. You may need to use other commands or tools to send emails from a shell script, such as sendmail
or a command-line email client.