[Tutor] Attaching an uploaded file to an email

Tim Wilson wilson at visi.com
Sun Feb 20 02:37:02 CET 2005


Hi everyone,

I'm working on a little Python CGI project, but I think I'm stuck on some of
the MIME magic. I've got a Web form that collects various bit of text and,
optionally, a file can be uploaded too. The file could be almost any kind of
document from jpeg to PDF.

The form data get passed to a Python CGI script that does some light text
manipulation and generates an email with some custom headers to a certain
address. If the user uploaded a file with the Web form, I want to have that
file included as an email attachment.

I've got it all working except for attaching the file to the email. I don't
understand how all of the MIME options work in the Python email module.

Here are two relevant sections of my code:

import cgi, smtplib, time
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
import cgitb; cgitb.enable()

# Collect form information
form = cgi.FieldStorage()
requestername = form["requestername"].value
fromaddr = form["email"].value
itemname = form["itemname"].value
description = form["description"].value
buildings = form.getlist("building")
room = form["room"].value
dateneeded = form["dateneeded"].value
po = form["po"].value
budgetcode = form["budgetcode"].value
attachment = form["attachment"].value
buildinglist = ", ".join(buildings)

**[ misc code snipped ]**

# Set some email headers
#msg = MIMEText(msgtext)
msg = MIMEMultipart()
msg['Subject'] = itemname
msg['From'] = "%s <%s>" % (requestername, fromaddr)
msg['To'] = toaddr
if len(buildings) != 0:
    for building in buildings:
        msg['X-HRT-Building'] = building
if po != "": msg['X-HRT-PO'] = po
if dateneeded != "":
    try:
        duedate = time.asctime(time.strptime(dateneeded, "%m/%d/%Y"))
        msg['X-HRT-Due-Date'] = duedate
    except ValueError:
        pass
msg.preamble = "Tech order request"
msg.epilogue = ""

# Attach the uploaded file
msg.attach(attachment)

# Send the message
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddr, msg.as_string(0))
server.quit()

In this program 'attachment' is the uploaded file.

I know there are some significant problems here, but I'm not making any
headway. Unless I'm reading them wrong, the docs for the email module don't
seem to cover a case like this.

Any ideas anyone?

-Tim

-- 
Tim Wilson
Twin Cities, Minnesota, USA
Educational technology guy, Linux and OS X fan, Grad. student, Daddy
mailto: wilson at visi.com   aim: tis270   blog: http://technosavvy.org/




More information about the Tutor mailing list