How to send e-mail from command line or script

From Salix OS
Jump to: navigation, search

Sometimes the ability to sending e-mail from the command line or a shell script might be useful, ie. to inform about the state of the server or just send an e-mail from your local machine when your usual mail server is off-line. This can be either done with the help of mailx - an application to send and read e-mails and sendmail - a mail transfer agent, or with email a small command line SMTP client. The difference between these methods consists in the fact that sendmail doesn`t require any external mail server to send an e-mail. Thus you can forge any e-mail you want. That is why some spam filters might block such home-made messages as possible spam. The other method - with email - allows to use an external SMTP server and should be safer.

Contents

Using sendmail/mailx

Install mailx and sendmail

 slapt-get -u
 slapt-get -i mailx sendmail

When the files are installed start the sendmail daemon:

/etc/rc.d/rc.sendmail start

or

service start sendmail

in order to start sendmail at system boot:

chmod a+x  /etc/rc.d/rc.sendmail

Sending e-mail

Using mailx is quite simple and self-explanitory:

mailx -s "subject" -a /path/to/atachment  recipient@server.com  <  body-of-mail.txt

The above command may be used from command line or a script. Sometimes you might need to define the sender address. Not all versions of mailx support this option:

 mailx -s "subject" -a /path/to/atachment -r "sender@server.org" receipient@server.com  <  body-of-mail.txt

Using email

If you don't want to install sendmail, you can use a very small console SMTP client, called email. Install the package with:

slapt-get -i email

Edit the /etc/email/email.conf file with your SMTP account's settings, including your username and password.You can use your ISP email for that, or gmail or whatever email service you're using that offers support for outgoing email and of course sendmail on your localhost, too . Basic usage is similar to that of mailx:

 email -s "Subject" recipient@server.com  <  body-of-mail.txt 

If you want to send an email to multiple addresses, you can specify the addresses in the same command, separating them with commas. If you don't have the email text ready yet, running:

 email -s "Subject" recipient@server.com

will open the default text editor and let you write it before sending.

Sometimes you might need to define the sender address. This can be done with "-n" option:

email -s "Subject" -n "sender@server.org" recipient@server.com  <  body-of-mail.txt