Send emails from shell script without local mailserver

How can I send email from a shellscript (usually cronjob) without running a mailserver on the same host. Using a smtp server. Running Ubuntu.

I looked a t various tutorials, but couldnt find a suitable approach (simple and secure).

Thanks

Sven


Solution 1:

You could install postfix or something else in relay-only mode and then use either mail(x) or mutt to send mail. Both can send mail from the command line.

A good option on Ubuntu might be nullmailer as MTA, as it is designed for relay-only operation.

Solution 2:

If it's ubuntu then you have python and can use it's smtplib module (means no MTA on same host). There is a little sample posted below to get you started (you might want to put the username/pass/config in an ini file, do some error checking and such, but the ''starttls'' line encrypts the rest of the smtp session if the server supports it.). That gives you simple and secure. It's possible to add attachments and so on with a little extra work.

You would call it like: mailsender.py "This is my message".

#!/usr/bin/python

import smtplib
import sys

message = sys.argv[1]

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login('[email protected]', 'password')
server.sendmail('[email protected]', '[email protected]', message)
server.rset()
server.quit()

You can call ''mailsender.py'' from your cron job or shellscripts.