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-11-08)

437.   How do I wash a feather comforter?   [n0b0dy/2006-08-13]
436.   How should an American use their cellphone on a short trip to Europe?   [strick/2006-07-25]
417.   What is the slashdot amnesia phenomenon?   [jake/2004-10-29]
410.   What is naked sushi? What is Nyataimori? What is Nyotaimori? Or how do I ask for a "Naked Sushi" bar?   [jake/2006-05-21] ( novalis/2005-03-30 )
391.   Is E.B. White of Strunk and White fame the same one who wrote Charlotte's Web?   [overcode/2003-11-03]
386.   What is Trinux ?   [brad/2003-10-06]
289.   How do I install a CPAN module in Perl?   [rupe/2001-11-21]
235.   How do I enable the diagnostic mode on a Garmin eTrex GPS?   [rupe/2001-05-30]
170.   Where can I find the Linux Kernel Wishlist?   [rupe/2001-01-31]
131.   What does Jesse do to anything after a fresh linux install?   [jesse/2000-10-08]
130.   How do I resolve the incompatibility of many older Mac applications with OS9?   [rupe/2000-10-08]
108.   How can i get custom ring tones onto my cell phone?   [jesse/2000-07-09]
63.   What does the accronym ENIAC stand for?   [simon/2000-02-19]
61.   Where is strick?   [strick/2001-05-30]
34.   What are some good World Wide Web facts I can impress my friends with?   [simon/2000-01-28]
17.   How can I make a didgeridoo for traveling?   [ult/2002-04-20]