I want to send an email from a Linux Shell script. What is the standard command to do this and do I need to set up any special server names?
The mail
command does that (who would have guessed ;-). Open your shell and enter man mail
to get the manual page for the mail
command for all the options available.
If the server is well configured, eg it has an up and running MTA, you can just use the mail command.
For instance, to send the content of a file, you can do this:
$ cat /path/to/file | mail -s "your subject" your@email.com
man mail
for more details.
On linux, mail utility can be used to send attachment with option "-a". Go through man pages to read about the option. For eg following code will send an attachment :
mail -s "THIS IS SUBJECT" -a attachment.txt name@domain.com <<< "Hi Buddy, Please find failure reports."
Generally, you'd want to use mail
command to send your message using local MTA (that will either deliver it using SMTP to the destination or just forward it into some more powerful SMTP server, for example, at your ISP). If you don't have a local MTA (although it's a bit unusual for a UNIX-like system to omit one), you can either use some minimalistic MTA like ssmtp.
ssmtp
is quite easy to configure. Basically, you'll just need to specify where your provider's SMTP server is:
# The place where the mail goes. The actual machine name is required
# no MX records are consulted. Commonly mailhosts are named mail.domain.com
# The example will fit if you are in domain.com and you mailhub is so named.
mailhub=mail
Another option is to use one of myriads scripts that just connect to SMTP server directly and try to post a message there, such as Smtp-Auth-Email-Script, smtp-cli, SendEmail, etc.
Admitting you want to use some smtp server, you can do:
export SUBJECT=some_subject
export smtp=somehost:someport
export EMAIL=someaccount@somedomain
echo "some message" | mailx -s "$SUBJECT" "$EMAIL"
Change somehost
, someport
, and someaccount@somedomain
to actual values that you would use.
No encryption and no authentication is performed in this example.