import sys import os from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def makeMessage(postdata, how): """Make a message with the undesired extra newlines: "postdata" is a dictionary describing data to include in the multipart MIME message Each postdata item maps a string name to either: - a string value; or - a file part specification of the form: {"filename": , # file to load content from "content": } # (optional) file content is used to load the content (can be overridden by ) and as the filename to report in the message. "how" is "good" or "bad" Inspiration: Perl's HTTP::Request module. http://aspn.activestate.com/ASPN/Reference/Products/ActivePerl/site/lib/HTTP/Request/Common.html """ message = MIMEMultipart(_subtype="form-data") for name, value in postdata.items(): if isinstance(value, dict): # This is a 'file' input. # Get content. if "content" in value: content = value["content"] else: fp = open(value["filename"], "rb") content = fp.read() fp.close() # Create text part. if how == "good": part = MIMEText(None) part.set_payload(content, "us-ascii") elif how == "bad": part = MIMEText(content) part.add_header("Content-Disposition", "form-data", name=name, filename=value["filename"]) else: # This is a non-'file' input # Do not use ctor to set payload to avoid adding a # trailing newline. if how == "good": part = MIMEText(None) part.set_payload(content, "us-ascii") elif how == "bad": part = MIMEText(value) part.add_header("Content-Disposition", "form-data", name=name) message.attach(part) message.epilogue = "" # Make sure body ends with a newline. return message.as_string() #---- mainline postdata = { "name": "pliers", "logfile": {"filename": r"D:\trentm\seuss.txt", "content": """\ one fish two fish three fish blue fish"""}, } bad = makeMessage(postdata, "bad") print "~~~~ bad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" sys.stdout.write(bad) print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" good = makeMessage(postdata, "good") print "~~~~ good ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" sys.stdout.write(good) print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ## A suggested MIMEText replacement: #from email.MIMENonMultipart import MIMENonMultipart #class MIMEText2(MIMENonMultipart): # """A better MIMEText than in Lib/email/MIMEText.py. # # Class for generating text/* type MIME documents.""" # # def __init__(self, _text, _subtype='plain', _charset='us-ascii'): # """Create a text/* type MIME document. # # _text is the string for this message object. # # _subtype is the MIME sub content type, defaulting to "plain". # # _charset is the character set parameter added to the Content-Type # header. This defaults to "us-ascii". Note that as a side-effect, the # Content-Transfer-Encoding header will also be set. # """ # MIMENonMultipart.__init__(self, 'text', _subtype, # **{'charset': _charset}) # self.set_payload(_text, _charset)