CGI email script

Michael Foord fuzzyman at gmail.com
Mon Nov 22 03:54:35 EST 2004


>     server.set_debuglevel(1)

Note that this line will cause debug messages to be printed before the
start of your HTML.

I've done a set of three functions for sending mail from CGI - one of
them should work ! I usually end up using the sendmailme function,
which isn't cross platform.

import os
import sys

SENDMAIL = "/usr/sbin/sendmail"             # location of sendmail on
the server

#############################################################
# Three alternative methods of sending email
# Which one works will depend on your server setup.

def mailme(to_email, email_subject, msg, from_email=None,
host='localhost'):
    """A straight email function using smtplib.
    With localhost set as host, this will work on many servers.
    """
    head = "To: %s\r\n" % to_email 
    if from_email:
        head = head + ('From: %s\r\n' % from_email)
    head = head + ("Subject: %s\r\n\r\n" % email_subject)
    msg = head + msg
    import smtplib
    server = smtplib.SMTP(host)
    server.sendmail(from_email, [to_email], msg)
    server.quit()
       

def sendmailme(to_email, email_subject, msg, from_email=None,
sendmail=SENDMAIL ):
    """Quick and dirty, pipe a message to sendmail.
    Can only work on UNIX type systems with sendmail.
    Will need the path to sendmail - can be specified in the
'SENDMAIL' default (see top of this script).
    """
    o = os.popen("%s -t" %  sendmail,"w")
    o.write("To: %s\r\n" %  to_email)
    if from_email:
        o.write("From: %s\r\n" %  from_email)
    o.write("Subject: %s\r\n" %  email_subject)
    o.write("\r\n")
    o.write("%s\r\n" % msg)
    o.close()                    

def loginmailme(to_email, email_subject, msg, host, user, password,
from_email=None ):
    """Email function for an smtp server you need to login to.
    Needs hostname, username, password etc.
    """
    head = "To: %s\r\n" % to_email 
    if from_email:
        head = head + ('From: %s\r\n' % from_email)
    head = head + ("Subject: %s\r\n\r\n" % email_subject)
    msg = head + msg

    import smtplib
    server = smtplib.SMTP(host)
    server.login(user, password)
    server.sendmail(from_email, [to_email], msg)
    server.quit()



More information about the Python-list mailing list