Saturday, November 7, 2009

A Sendmail replacement in Python

I know I blog about odd things, but it's just that those odd things happen to me! The problem we have now is the following: we need to have a sendmail-like command that will send email through an external SMTP server. Why? Well its a long story that can be resumed to the fact that I just don't want to install Sendmail into my VoIP server ;).

So instead of doing what everyone would do (apt-get install sendmail) I wrote a simple script in Python that works somewhat like Sendmail does, with the exception that it just forwards everything to another server. I *could* make it work without an external server, but that would require to resolve the DNS of the destination server and to find the MX registers... and I'm lazy. Plus that would require an external Python Module to do the DNS resolution, and I wanted my script to be pure-Python with no dependencies other than the Python library. Anyway if anyone, ever, needs a script to do the DNS thing, ask and I'll do it *sigh*.

So here comes the script. The script accepts the sendmail -t parameter so the "To" header from the Email is used to specify the recipients, otherwise recipients should be specified by command line.

#!/usr/bin/python

import email
import smtplib
import sys

SMTP_SERVER="YourMailServer.com"
SMTP_USER="YourUser"
SMTP_PASS="Ssh-Sekrat!"

def sendmail(from_addr, to_addrs, msg):
    smtp = smtplib.SMTP(SMTP_SERVER)
    smtp.login(SMTP_USER, SMTP_PASS)
    smtp.sendmail(from_addr, to_addrs, msg)
    smtp.quit()

def main():
    msgstr = sys.stdin.read()

    msg = email.message_from_string(msgstr)
    if sys.argv[1] == "-t":
        to_addrs = msg["To"]
    else:
        to_addrs = sys.argv[1:]
    sendmail(msg["From"], to_addrs, msgstr)

main()


Thats it! To test it:

./sendmail.py someone@somewhere.com
From: your@friend.com
Subject: Hello!

Hello! Hows life?
<CTRL+D>

I hope you liked it, happy hacking!