faqts : Computers : Programming : Languages : Python : Modules : smtplib

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

111 of 125 people (89%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I use the smtplib module to send email from Python?
How can I send mail using the os module?
How can I send mail through python?

Jun 30th, 2000 11:33
George Jansen, Nathan Wallace, unknown unknown, http://www.python.org/doc/FAQ.html#4.71


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

Check out the os module doc for more info:

  http://www.python.org/doc/current/lib/module-os.html


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.

    http://www.python.org/doc/current/lib/module-smtplib.html

On Windows 9x systems, you may also use the COM interface. We have 
recently used PythonWin to (what else?) spam a number of recipients 
over Novell GroupWise. It took very little time to work this out.