Tim Wilson wrote:

Hi everyone,


Hi Tim,

I'm a newb, first time posting, so please take any of the following advice at face value....

# 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


based on this cookbook recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/273844, it looks like cgi.FieldStorage() returns a file-like object for file input fields, having .filename and .file attributes. the file attribute has a read() method which may be useful. having never used cgi I'm not sure what .value returns for file input fields, don't know if this is of any consequence.

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 = ""


if you know that the attachment will always be a text file and your assignment of 'attachment' looks like this:

   attachment = form["attachment"]

then you might try the following (untested):

part = MIMEText(attachment.file.read())
# if I understand correctly, the 'Content-Disposition' header is necessary to make the file
# appear in the message as an attachment, otherwise it may occupy the msg body.
part.add_header('Content-Disposition', 'attachment', filename=attachment.filename)
msg.attach(part)


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


there's a great example in the email module docs if you're dealing with more than just text files :
http://docs.python.org/lib/node578.html (3rd example, using the mimetypes module)


I have collected code snippets from various sources (python docs, ASPNs python cookbook) into a basic MIMEMailer class, that I use fairly regularly in hobby projects. If anyone is interested, I'd be happy to share, or post it here.

HTH,
Marty


_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor

Reply via email to