Problem
Send an email alert from a Bash script.
tl;dr
Add this to your bash script:
mail -s 'Email Subject Here' sample@email.com << EOF
This is an automatic alert to let you know the Eagle has landed. Over.
EOF
Solution
Default installation of CentOS typically comes with Postfix already installed. As such, CentOS is quite capable of sending mail without any further configuration. Any email you send will come from the address user@hostname.domain if you have not configured an SMTP server. You may also need to whitelist the address in your target mailbox's spam settings.
If you just need to manually send an email from a shell prompt, all you need to do is type in the mail command with the target email:
mail sample@email.com
(For more details, see Sending Mail from a Linux Command Line)
However, this requires user input, which you cannot provide in an automated script. Therefore, you need to add the required arguments to the script. The -s argument is used for the subject:
mail -s 'Eagle Landing Report'
Then, you need to add the main body (which may consist of multiple lines). You use that with End-of-File tags.
EOF Tags
EOF, or End-of-File tags are used in programming to tell the system no more data can be read from a source, such as a file, data stream, or command line. They are otherwise equivalent to Ctrl-D that is otherwise required to manually send the email.
Use them in conjunction with << tags, or input stream redirection tags, to delimit the beginning and end of your email:
<< EOF
Line 1 of my email
Line 2 of my email
Something something Danger Zone
Last line of my email
EOF
Sample email script
The full script you would look similar to this:
#!/bin/bash
mail -s 'Eagle Landing Report' jason.bourne@cia.gov << EOF
Hello,
I would like to inform you that the Eagle has landed.
All relevant instructions have been forwarded to previously designated operatives.
You have the green light for the operation.
Yours Sincerely,
Pamela Landy
Deputy Director/Operations
Central Intelligence Agency
EOF