Send emails from shell script without local mailserver

6,615

Solution 1

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.

Solution 2

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.

Share:
6,615

Related videos on Youtube

javadude
Author by

javadude

Working with all kind of opensource products. Main focus on Java, EE, Glassfish, PostgreSQL, Ajax with ZK, Groovy, Mule. Working as System Architect in the Airport Industry.

Updated on September 17, 2022

Comments

  • javadude
    javadude almost 2 years

    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

  • David Z
    David Z about 14 years
    ssmtp is another option that, as far as I can tell, does pretty much the same thing as nullmailer. I'd recommend something in that vein.
  • javadude
    javadude about 14 years
    I go for the groovy version (stackoverflow.com/questions/1990454/…)