Logo
Blog: Command Line SMTP from Python

Sending SMTP relay messages out through Python is very straight forward.

If your SMTP server is set to accept open relays from your server/client (not necessarily a good idea), you can just do the following:

 
#!/usr/bin/python
 
import smtplib, sys
 
if len(sys.argv) != 5:
  print "You must call me like:"
  print "   mailme from to subject msgfile"
  sys.exit()
 
fromaddr = sys.argv[1]
toaddr = sys.argv[2]
subject = sys.argv[3]
msgfile = sys.argv[4]
 
try:
  f = open(msgfile)
  msg = f.read()
except:
  print "Invalid Message File: " + msgfile
  sys.exit()
 
m = "From: %s\r\nTo: %s\r\nSubject: %s\r\nX-Mailer: My-Mail\r\n\r\n" \
  % (fromaddr, toaddr, subject)
 
smtp = smtplib.SMTP()
smtp.connect('10.34.20.251')
smtp.sendmail(fromaddr, toaddr, m+msg)
smtp.close()
 

Note: this is a very minimal example and should/could do a lot more fancy error checking and stuff. Hopefully it's useful to at least get you rolling though.

Blog Index