Hi I recently started using python for work and was tasked with creating a mailer script for one of our linux servers.
I found a number of good examples on the web for different mailer app implementations and eventually came to the code below. Can anyone advise me on good practices and anything I may have missed when writing this code that could be useful/avoid headaches.
I should mention this app is ran from the shell and all output(error or otherwise) is piped to a log for later parsing and the intention is not to have any sensitive data sent to the script as a parameter to avoid security concerns.
import smtplib from datetime import date def send_message(addr, to, msg): try: server = smtplib.SMTP('sending.server.net',587) except smtplib.socket.gaierror: return 'connect_err' try: server.ehlo() server.starttls() server.ehlo() server.login('firstname.lastname@example.org','password') except smtplib.SMTPAuthenticationError: server.quit() return 'login_err' try: server.sendmail(addr, to, msg) print 'Message sending successful' return True except Exception: return 'send_err' finally: server.quit() fromaddr = 'email@example.com' now = date.today().strftime("%d/%m/%y") msg = ("From:%s\r\nTo: firstname.lastname@example.org\r\nSubject: Subject of the message\r\n\r\n Hello,\r\nThis is the message body.\r\n\r\nThank you." % (fromaddr)) print now+'\n' print msg+'\n' fromaddr="email@example.com" toaddr="firstname.lastname@example.org" success = send_message(fromaddr,toaddr,msg) if success=='connect_err': print 'Error connecting to host' if success=='login_err': print 'Error logging in' if success=='send_err': print 'Error sending message'