Search:  
Gentoo Wiki

HOWTO_Send_emails_with_shell_scripts

Contents

Introduction

I wrote this HOWTO because I wanted one before I have to figure it out for myself :-)

Sending emails with shell scripts can be very useful. As an example: you can put a script into cron to send the output of "df -h" once a day to you.

Programs we need

Installing postfix

First we need to emerge postfix

emerge postfix

Configure postfix

Edit the file /etc/postfix/main.cf

nano /etc/postfix/main.cf

Don't be scared, the only thing you have to do is uncomment and edit the line:

myhostname = foo.bar

Some email providers like gmx try to resolve this name and only accept an email if they succeed, so if you have no domain you can use dyndns (Dynamic DNS).

Use newaliases to set your configuration

newaliases

Add Postfix to default runlevel

rc-update add postfix default

Start Postfix

/etc/init.d/postfix start

Try it

echo -e "subject: Test Email\nJust testing\n." | sendmail -f email_address_of_sender email_address_of_receiver

(The dot is terminating the message body.)

if it doesn't work perhaps you find some useful informations in /var/log/mail/current

Now we are ready to use sendmail in scripts.

Example

you need cron for that:

emerge vixie-cron
rc-update add vixie-cron default
/etc/init.d/vixie-cron start

create a shell-script with your favorite editor:

File: /etc/cron.daily/status-report
#!/bin/sh

tmp=/tmp/status-report-`date +%F`
touch $tmp && chmod 600 $tmp

echo -e "subject: status-report-`date +%F`\n" > $tmp
echo -e "\n -- Free Disk Space -- " >> $tmp
df -h >> $tmp
echo -e "\n -- Ram -- " >> $tmp
free -m >> $tmp
echo -e "\n -- Processes -- " >> $tmp
ps auxf >> $tmp
echo -e "\n -- Uptime -- " >> $tmp
uptime >> $tmp

sendmail -f sender_email_address your_email_address < $tmp

rm $tmp

change permissions:

chmod a+x /etc/cron.daily/status-report

now you will get a status report of your system once a day.

Note: It may be necessary to include the path to sendmail in this script. (ie /usr/sbin/sendmail)

Mailaliases

some programs like sudo or cron try to send emails to local users like root. If you want to get those mails you have to edit the file /etc/mail/aliases.

# Well-known aliases -- these should be filled in!
root:           your_email_address
operator:       your_email_address

you can also add new aliases:

scripts:       your_email_address

so the next time you use sendmail you can use:

sendmail -f sender_adress scripts

run newaliases to set the new settings

newaliases
Retrieved from "http://www.gentoo-wiki.info/HOWTO_Send_emails_with_shell_scripts"

Last modified: Thu, 02 Oct 2008 22:15:00 +0000 Hits: 19,552