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.

Cheers, Kerry

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('account@server.net','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 = 'account@server.net'
now = date.today().strftime("%d/%m/%y")
msg = ("From:%s\r\nTo: you@your.com\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="account@server.net"
toaddr="you@your.com"
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'

This worked for me:

import smtplib
from datetime import date
smtpserver = ('smtp.gmail.com',587)
fromaddr = ""
toaddr = ""
password = ''

def send_message(addr, to, msg):
    try:
        server = smtplib.SMTP(*smtpserver)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(fromaddr,password)
        server.sendmail(addr, to, msg)
    except:
        raise
    finally:
        server.quit()

now = date.today().strftime("%d/%m/%y")
subject = 'Subject of the message'
msg = '\n'.join(("From:%s",
                  "To: %s",
                  "Subject:  %s\n")) % (fromaddr, toaddr, subject)

greeting = 'Hello,'
body = 'This is the message body.'
bye = 'Thank you.'
msg += '\n\n'.join((greeting, body, bye))

print now
print msg
send_message(fromaddr,toaddr,msg)

It raises proper errors instead of messing them, and uses normal newlines.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.