by rupe

How do I send mail from a Python script?

Here's the answer, courtesy of the FAQ at python.org, located here

On Unix, it's very simple, using sendmail. The location of the sendmail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The sendmail manual page will help you out. Here's some sample code:

  SENDMAIL = "/usr/sbin/sendmail" # sendmail location
  import os
  p = os.popen("%s -t" % SENDMAIL, "w")
  p.write("To: cary@ratatosk.org\n")
  p.write("Subject: test\n")
  p.write("\n") # blank line separating headers from body
  p.write("Some text\n")
  p.write("some more text\n")
  sts = p.close()
  if sts != 0:
      print "Sendmail exit status", sts
On non-Unix systems (and on Unix systems too, of course!), you can use SMTP to send mail to a nearby mail server. A library for SMTP (smtplib.py) is included in Python 1.5.1; in 1.5.2 it will be documented and extended. Here's a very simple interactive mail sender that uses it:

    import sys, smtplib
    fromaddr = raw_input("From: ")
    toaddrs  = string.splitfields(raw_input("To: "), ',')
    print "Enter message, end with ^D:"
    msg = ''
    while 1:
        line = sys.stdin.readline()
        if not line:
            break
        msg = msg + line
    # The actual mail send
    server = smtplib.SMTP('localhost')
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()
This method will work on any host that supports an SMTP listener; otherwise, you will have to ask the user for a host.

 


 
Read more of   The Yak's Frequently Questioned Answers   (mod.2008-06-12)

429.   why does my 802.11g network seem to die around Uniden 2.4ghz phones?   [jake/2006-05-19]
420.   How can I use a new 40 Gig iPod with Debian and USB   [jake/2005-03-01]
291.   Should I solder my Sound Card into my computer?   [strick/2002-02-04]
277.   What does K-Rad mean? is there a modern alternative to k-rad?   [mennonite/2001-10-08]
271.   I am stupid and forgot my root password for my OpenBSD box. Now what?!?!   [ross/2001-09-05]
264.   What started in 1984?   [strick/2001-08-10] ( macki/2001-09-04 robey/2001-08-22 )
254.   how do i setup my orinoco wirelss card with linux 2.4.x?   [jesse/2001-07-03]
200.   where can i find a good resource for radio repeaters in norther california   [jesse/2001-03-13]
183.   What are the real lyrics for the poem "Big Rock Candy Mountains"?   [rupe/2001-02-19] ( jesse/2001-06-29 )
174.   why doesnt an image change in a java applet when it changes on the server?   [jesse/2001-02-10]
170.   Where can I find the Linux Kernel Wishlist?   [rupe/2001-01-31]
168.   What's the Official Fag Razor of the YAK?   [strick/2001-01-29]
151.   How can I tell ICANN to screw off?   [fury/2000-12-09]
46.   What is Ross' natural hair color?   [macki/2000-02-03]