def test_encode(self): for p, e in self.STRINGS: infp = cStringIO.StringIO(p) outfp = cStringIO.StringIO() if not test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=305368"): quopri.encode(infp, outfp, quotetabs=False) self.assertTrue(outfp.getvalue() == e)
def quopri_encode(input, errors = 'strict'): assert errors == 'strict' f = StringIO(str(input)) g = StringIO() quopri.encode(f, g, 1) output = g.getvalue() return (output, len(input))
def __init__(self, http_response, request_id): HTTPMessage.__init__(self) self.set_type("application/http-response") self.add_header("Multipart-Request-ID", str(request_id)) self.add_header("Content-transfer-encoding", "quoted-printable") payload = StringIO() quopri.encode(StringIO(http_response), payload, quotetabs=False) self.set_payload(payload.getvalue()) payload.close()
def __init__(self, http_request, request_id): HTTPMessage.__init__(self) self.set_type('application/http-request') self.add_header('Multipart-Request-ID', str(request_id)) self.add_header('Content-transfer-encoding', 'quoted-printable') payload = StringIO() quopri.encode(StringIO(http_request), payload, quotetabs=False) self.set_payload(payload.getvalue()) payload.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", user=None, password=None): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text, _charset='utf-8') ) for fileName in files: contentType,ignored=mimetypes.guess_type(fileName) if contentType==None: # If no guess, use generic opaque type contentType="application/octet-stream" contentsEncoded=cStringIO.StringIO() f=open(fileName,"rb") mainType=contentType[:contentType.find("/")] if mainType=="text": cte="quoted-printable" quopri.encode(f,contentsEncoded,1) # 1 for encode tabs else: cte="base64" base64.encode(f,contentsEncoded) f.close() subMsg=email.Message.Message() subMsg.add_header("Content-type",contentType,name=flatten_name(fileName)) subMsg.add_header("Content-transfer-encoding",cte) subMsg.set_payload(contentsEncoded.getvalue()) contentsEncoded.close() msg.attach(subMsg) # part = MIMEBase('application', "octet-stream") # part.set_payload( open(file,"rb").read() ) # Encoders.encode_base64(part) # part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) # msg.attach(part) # print server smtp = smtplib.SMTP(server, 587) # smtp.set_debuglevel(1) smtp.ehlo() settings = HandshakeSettings() smtp.starttls() if (user != None and password != None): smtp.login(user, password) print "Sending mail to " + msg['To'] smtp.sendmail(send_from, send_to, msg.as_string()) print "mail sent." smtp.close() print "done"
def _qencode(s): if not s: return s hasnewline = (s[-1] == '\n') infp = StringIO(s) outfp = StringIO() _quopri.encode(infp, outfp, quotetabs=1) # Python 2.x's encode() doesn't encode spaces even when quotetabs==1 value = outfp.getvalue().replace(' ', '=20') if not hasnewline and value[-1] == '\n': return value[:-1] return value
def quopri_encode(input, errors='strict'): """Encode the input, returning a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' f = StringIO(input) g = StringIO() quopri.encode(f, g, 1) output = g.getvalue() return (output, len(input))
def quopri_encode(input, errors='strict'): """Encode the input, returning a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' # using str() because of cStringIO's Unicode undesired Unicode behavior. f = StringIO(str(input)) g = StringIO() quopri.encode(f, g, quotetabs=True) output = g.getvalue() return (output, len(input))
def standard_message(self, to, subject, content, author=None): """Send a standard message. Arguments: - to: a list of addresses usable by rfc822.parseaddr(). - subject: the subject as a string. - content: the body of the message as a string. - author: the sender as a (name, address) tuple """ message, writer = self.get_standard_message(to, subject, author) writer.addheader("Content-Transfer-Encoding", "quoted-printable") body = writer.startbody("text/plain; charset=utf-8") content = StringIO(content) quopri.encode(content, body, 0) self.smtp_send(to, message)
def main(): mainMsg=email.Message.Message() mainMsg["To"]=toAddr mainMsg["From"]=fromAddr mainMsg["Subject"]="Directory contents" mainMsg["Date"]=email.Utils.formatdate(localtime=1) mainMsg["Message-ID"]=email.Utils.make_msgid() mainMsg["Mime-version"]="1.0" mainMsg["Content-type"]="Multipart/mixed" mainMsg.preamble="Mime message\n" mainMsg.epilogue="" # To ensure that message ends with newline firstSubMsg=email.Message.Message() firstSubMsg["Content-type"]="text/plain" firstSubMsg["Content-transfer-encoding"]="7bit" firstSubMsg.set_payload("Files from directory\n") mainMsg.attach(firstSubMsg) # Get names of plain files fileNames=[f for f in os.listdir(os.curdir) if os.path.isfile(f)] for fileName in fileNames: contentType,ignored=mimetypes.guess_type(fileName) if contentType==None: # If no guess, use generic opaque type contentType="application/octet-stream" contentsEncoded=cStringIO.StringIO() f=open(fileName,"rb") mainType=contentType[:contentType.find("/")] if mainType=="text": cte="quoted-printable" quopri.encode(f,contentsEncoded,1) # 1 for encode tabs else: cte="base64" base64.encode(f,contentsEncoded) f.close() subMsg=email.Message.Message() subMsg.add_header("Content-type",contentType,name=fileName) subMsg.add_header("Content-transfer-encoding",cte) subMsg.set_payload(contentsEncoded.getvalue()) contentsEncoded.close() mainMsg.attach(subMsg) f=open(outputFile,"wb") f.write(mainMsg.as_string()) f.close() return None
def send(self, report_file, from_addr, to_addrs): if self.init == False: print("Instance not properly instanitiated") return -1 self.msgs = [email.Message.Message() for to in to_addrs] for msg , to in zip(self.msgs, to_addrs): msg["From"] = from_addr msg["To"] = to msg["Subject"] = "Auto-Test Result Reporting" msg["MIME-Version"] = "1.0" msg["Content-Type"] = "Multipart/mixed" msg.preamble = "MIME Message" msg.epilogue = "" content_type, ignored = mimetypes.guess_type(report_file) if content_type == None: content_type = "Application/octet-stream" content_encoded = cStringIO.StringIO() with open(report_file, "rb") as f: main_type = content_type[:content_type.find("/")] if main_type == "text": cte = "quoted-printable" quopri.encode(f, content_encoded, 1) else: cte = "base64" base64.encode(f, content_encoded) f.close() sub_msg = email.Message.Message() sub_msg.add_header("Content-Type", content_type, name = report_file) sub_msg.add_header("Content-Transfer-Encoding", cte) sub_msg.set_payload(content_encoded.getvalue()) content_encoded.close() for msg, to in zip(self.msgs, to_addrs): msg.attach(sub_msg) f = StringIO.StringIO() g = email.Generator.Generator(f) g.flatten(msg) try: self.smtp.sendmail(from_addr, to, f.getvalue()) except Exception: print("send to %s failed" % to) f.close()
def emailTurnin(self): #Get email information try: addr = JESAddressFinder.JESAddressFinder() taEmail = addr.getTargetAddress(self.gtNumber, self.hwTitle) if(taEmail == None): raise StandardError, "Could not find an e-mail to send assignment." return filehandle = open(self.zipFile,"rb") #CONSTRUCT EMAIL #Build the email from all the parts of information: subject = "%s : %s : %s : %s" % \ (self.hwTitle, self.studentName, self.gtNumber, self.fileName) msgBody = 'From: %s\n' % self.studentEmail msgBody += 'Subject: %s\n' % subject file = StringIO.StringIO() mime = MimeWriter.MimeWriter(file) mime.addheader("Mime-Version","1.0") mime.startmultipartbody("mixed") part=mime.nextpart() part.addheader("Content-Transfer-Encoding","quoted-printable") part.startbody("text/plain") quopri.encode(StringIO.StringIO("An Assignment Submission from "+self.studentName),file,0) quopri.encode(StringIO.StringIO("Notes to TA: "),file,0) #quopri.encode(StringIO.StringIO(notes),file,0) part = mime.nextpart() part.addheader("Content-Transfer-Encoding","base64") part.startbody('application/x-zip-compressed; name='+self.zipFile) base64.encode(filehandle, file) mime.lastpart() msgBody += file.getvalue() filehandle.close() #END CONSTRUCT EMAIL #SEND EMAIL: servObj = smtplib.SMTP(self.mailServer) servObj.sendmail(self.studentEmail, taEmail, msgBody) except: print "Student E-mail: " + self.studentEmail + "\n" import sys a,b,c=sys.exc_info() print a,b,c raise StandardError, "Error emailing assignment."
def main(): main_msg = email.Message.Message() main_msg["To"] = T_ADDR main_msg["From"] = F_ADDR main_msg["Subject"] = "Directory contents" main_msg["Mime-version"] = "1.0" main_msg["Content-type"] = "Multipart/mixed" main_msg.preamble = "Mime message\n" main_msg.epilogue = "" file_names = [f for f in os.listdir(os.curdir) if os.path.isfile(f)] for file_name in file_names: content_type,ignored = mimetypes.guess_type(file_name) if content_type is None: content_type = "application/octet-stream" contents_encoded = cStringIO.StringIO() with open(file_name,"rb") as f: main_type = content_type[:content_type.find("/")] if main_type == "text": cte = "quoted-printable" quopri.encode(f,contents_encoded,True) else: cte = "base64" base64.encode(f,contents_encoded) sub_msg = email.Message.Message() sub_msg.add_header("Content-type",content_type,name=file_name) sub_msg.add_header("Content-transfer-encoding",cte) sub_msg.set_payload(contents_encoded.getvalue()) contents_encoded.close() main_msg.attach(sub_msg) body_content = email.Message.Message() body_content.set_type("text/plain") body_content.set_payload("hello word") main_msg.attach(body_content) f = open(output_file,"wb") g = email.Generator.Generator(f) g.flatten(main_msg) f.close() return None
def write(self, data, mimetype="text/plain"): "Write data from string or file to message" # data is either an opened file or a string if type(data) is type(""): file = StringIO.StringIO(data) else: file = data data = None part = self.mime.nextpart() typ, subtyp = string.split(mimetype, "/", 1) if typ == "text": # text data encoding = "quoted-printable" encoder = lambda i, o: quopri.encode(i, o, 0) if data and not must_quote(data): # copy, don't encode encoding = "7bit" encoder = None else: # binary data (image, audio, application, ...) encoding = "base64" encoder = base64.encode # # write part headers if encoding: part.addheader("Content-Transfer-Encoding", encoding) part.startbody(mimetype) # # write part body if encoder: encoder(file, self.file) elif data: self.file.write(data) else: while 1: data = infile.read(16384) if not data: break outfile.write(data)
def attach(self, chemin_fichier): raise NotImplementedError fileName = chemin_fichier.split( '/' )[-1] contentType,ignored=mimetypes.guess_type(fileName) if contentType==None: # If no guess, use generic opaque type contentType="application/octet-stream" contentsEncoded=cStringIO.StringIO() f=open(chemin_fichier,"rb") mainType=contentType[:contentType.find("/")] if mainType=="text": cte="quoted-printable" quopri.encode(f,contentsEncoded,1) # 1 for encode tabs else: cte="base64" base64.encode(f,contentsEncoded) f.close() subMsg=email.Message.Message() subMsg.add_header("Content-type",contentType,name=fileName) subMsg.add_header("Content-transfer-encoding",cte) subMsg.set_payload(contentsEncoded.getvalue()) contentsEncoded.close() self.__email.attach( subMsg )
def main(): mainMsg = email.Message.Message() mainMsg["To"] = toAddr mainMsg["From"] = fromAddr mainMsg["Subject"] = "Directory contents" mainMsg["Mime-version"] = "1.0" mainMsg["Content-type"] = "Multipart/mixed" mainMsg.preamble = "Mime message\n" mainMsg.epilogue = "" # to ensure that message ends with newline # Get names of plain files (not subdirectories or special files) fileNames = [f for f in os.listdir(os.curdir) if os.path.isfile(f)] for fileName in fileNames: contentType, ignored = mimetypes.guess_type(fileName) if contentType is None: # If no guess, use generic opaque type contentType = "application/octet-stream" contentsEncoded = cStringIO.StringIO() f = open(fileName, "rb") mainType = contentType[:contentType.find("/")] if mainType=="text": cte = "quoted-printable" quopri.encode(f, contentsEncoded, 1) # 1 to also encode tabs else: cte = "base64" base64.encode(f, contentsEncoded) f.close() subMsg = email.Message.Message() subMsg.add_header("Content-type", contentType, name=fileName) subMsg.add_header("Content-transfer-encoding", cte) subMsg.set_payload(contentsEncoded.getvalue()) contentsEncoded.close() mainMsg.attach(subMsg) f = open(outputFile, "wb") g = email.Generator.Generator(f) g.flatten(mainMsg) f.close() return None
def encode(input, output, encoding): if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encodetab.has_key(encoding): pipethrough(input, encodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
def encode(input, output, encoding): if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encoding in ('7bit', '8bit'): return output.write(input.read()) if encoding in encodetab: pipethrough(input, encodetab[encoding], output) else: raise ValueError, 'unknown Content-Transfer-Encoding: %s' % encoding
def encode(input, output, encoding): """Encode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encoding in ('7bit', '8bit'): output.write(input.read()) if encodetab.has_key(encoding): pipethrough(input, encodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
def send_message(self, nodeid, msgid, note, sendto, from_address=None, bcc_sendto=[]): '''Actually send the nominated message from this node to the sendto recipients, with the note appended. ''' users = self.db.user messages = self.db.msg files = self.db.file if msgid is None: inreplyto = None messageid = None else: inreplyto = messages.get(msgid, 'inreplyto') messageid = messages.get(msgid, 'messageid') # make up a messageid if there isn't one (web edit) if not messageid: # this is an old message that didn't get a messageid, so # create one messageid = "<%s.%s.%s%s@%s>" % (time.time(), random.random(), self.classname, nodeid, self.db.config.MAIL_DOMAIN) if msgid is not None: messages.set(msgid, messageid=messageid) # compose title cn = self.classname title = self.get(nodeid, 'title') or '%s message copy' % cn # figure author information if msgid: authid = messages.get(msgid, 'author') else: authid = self.db.getuid() authname = users.get(authid, 'realname') if not authname: authname = users.get(authid, 'username', '') authaddr = users.get(authid, 'address', '') if authaddr and self.db.config.MAIL_ADD_AUTHOREMAIL: authaddr = " <%s>" % straddr(('', authaddr)) elif authaddr: authaddr = "" # make the message body m = [''] # put in roundup's signature if self.db.config.EMAIL_SIGNATURE_POSITION == 'top': m.append(self.email_signature(nodeid, msgid)) # add author information if authid and self.db.config.MAIL_ADD_AUTHORINFO: if msgid and len(self.get(nodeid, 'messages')) == 1: m.append( _("New submission from %(authname)s%(authaddr)s:") % locals()) elif msgid: m.append( _("%(authname)s%(authaddr)s added the comment:") % locals()) else: m.append(_("Change by %(authname)s%(authaddr)s:") % locals()) m.append('') # add the content if msgid is not None: m.append(messages.get(msgid, 'content', '')) # get the files for this message message_files = [] if msgid: for fileid in messages.get(msgid, 'files'): # check the attachment size filename = self.db.filename('file', fileid, None) filesize = os.path.getsize(filename) if filesize <= self.db.config.NOSY_MAX_ATTACHMENT_SIZE: message_files.append(fileid) else: base = self.db.config.TRACKER_WEB link = "".join((base, files.classname, fileid)) filename = files.get(fileid, 'name') m.append( _("File '%(filename)s' not attached - " "you can download it from %(link)s.") % locals()) # add the change note if note: m.append(note) # put in roundup's signature if self.db.config.EMAIL_SIGNATURE_POSITION == 'bottom': m.append(self.email_signature(nodeid, msgid)) # encode the content as quoted-printable charset = getattr(self.db.config, 'EMAIL_CHARSET', 'utf-8') m = '\n'.join(m) if charset != 'utf-8': m = unicode(m, 'utf-8').encode(charset) content = cStringIO.StringIO(m) content_encoded = cStringIO.StringIO() quopri.encode(content, content_encoded, 0) content_encoded = content_encoded.getvalue() # make sure the To line is always the same (for testing mostly) sendto.sort() # make sure we have a from address if from_address is None: from_address = self.db.config.TRACKER_EMAIL # additional bit for after the From: "name" from_tag = getattr(self.db.config, 'EMAIL_FROM_TAG', '') if from_tag: from_tag = ' ' + from_tag subject = '[%s%s] %s' % (cn, nodeid, title) author = (authname + from_tag, from_address) # send an individual message per recipient? if self.db.config.NOSY_EMAIL_SENDING != 'single': sendto = [[address] for address in sendto] else: sendto = [sendto] # now send one or more messages # TODO: I believe we have to create a new message each time as we # can't fiddle the recipients in the message ... worth testing # and/or fixing some day first = True for sendto in sendto: # create the message mailer = Mailer(self.db.config) message, writer = mailer.get_standard_message( sendto, subject, author) # set reply-to to the tracker tracker_name = self.db.config.TRACKER_NAME if charset != 'utf-8': tracker = unicode(tracker_name, 'utf-8').encode(charset) tracker_name = encode_header(tracker_name, charset) writer.addheader('Reply-To', straddr((tracker_name, from_address))) # message ids if messageid: writer.addheader('Message-Id', messageid) if inreplyto: writer.addheader('In-Reply-To', inreplyto) # Generate a header for each link or multilink to # a class that has a name attribute for propname, prop in self.getprops().items(): if not isinstance(prop, (hyperdb.Link, hyperdb.Multilink)): continue cl = self.db.getclass(prop.classname) if not 'name' in cl.getprops(): continue if isinstance(prop, hyperdb.Link): value = self.get(nodeid, propname) if value is None: continue values = [value] else: values = self.get(nodeid, propname) if not values: continue values = [cl.get(v, 'name') for v in values] values = ', '.join(values) writer.addheader( "X-Roundup-%s-%s" % (self.classname, propname), values) if not inreplyto: # Default the reply to the first message msgs = self.get(nodeid, 'messages') # Assume messages are sorted by increasing message number here if msgs[0] != nodeid: inreplyto = messages.get(msgs[0], 'messageid') if inreplyto: writer.addheader('In-Reply-To', inreplyto) # attach files if message_files: part = writer.startmultipartbody('mixed') part = writer.nextpart() part.addheader('Content-Transfer-Encoding', 'quoted-printable') body = part.startbody('text/plain; charset=%s' % charset) body.write(content_encoded) for fileid in message_files: name = files.get(fileid, 'name') mime_type = files.get(fileid, 'type') content = files.get(fileid, 'content') part = writer.nextpart() if mime_type == 'text/plain': part.addheader('Content-Disposition', 'attachment;\n filename="%s"' % name) try: content.decode('ascii') except UnicodeError: # the content cannot be 7bit-encoded. # use quoted printable part.addheader('Content-Transfer-Encoding', 'quoted-printable') body = part.startbody('text/plain') body.write(quopri.encodestring(content)) else: part.addheader('Content-Transfer-Encoding', '7bit') body = part.startbody('text/plain') body.write(content) else: # some other type, so encode it if not mime_type: # this should have been done when the file was saved mime_type = mimetypes.guess_type(name)[0] if mime_type is None: mime_type = 'application/octet-stream' part.addheader('Content-Disposition', 'attachment;\n filename="%s"' % name) part.addheader('Content-Transfer-Encoding', 'base64') body = part.startbody(mime_type) body.write(base64.encodestring(content)) writer.lastpart() else: writer.addheader('Content-Transfer-Encoding', 'quoted-printable') body = writer.startbody('text/plain; charset=%s' % charset) body.write(content_encoded) if first: mailer.smtp_send(sendto + bcc_sendto, message) else: mailer.smtp_send(sendto, message) first = False
def test_encode(self): for p, e in self.STRINGS: infp = io.BytesIO(p) outfp = io.BytesIO() quopri.encode(infp, outfp, quotetabs=False) self.assertEqual(outfp.getvalue(), e)
def quopri_encode(input, errors='strict'): assert errors == 'strict' f = BytesIO(input) g = BytesIO() quopri.encode(f, g, quotetabs=True) return (g.getvalue(), len(input))
def encodestring(instring, tabs=0): outfile = StringIO.StringIO() quopri.encode(StringIO.StringIO(instring), outfile, tabs) return outfile.getvalue()
def encodestring(instring, tabs=0): outfile = io.StringIO() print(io.StringIO(instring), type(io.StringIO(instring))) print(outfile, type(outfile)) quopri.encode(io.StringIO(instring), outfile, tabs) return outfile.getvalue()
def makemessage(self, tofield=None): if not tofield: tofield = self.widget.tofield.get_text() out = cStringIO.StringIO() mw = MimeWriter.MimeWriter(out) # Write standard header. mw.addheader("X-Mailer", "SQmaiL (http://sqmail.sourceforge.net)") mw.addheader("From", self.widget.fromfield.get_text()) mw.addheader("To", tofield) mw.addheader("Subject", self.widget.subjectfield.get_text()) mw.addheader("MIME-Version", "1.0") # Send the X-Face? if sqmail.preferences.get_sendxface(): mw.addheader("X-Face", sqmail.preferences.get_outgoingxfaceicon()) # If we were replying to something, write the in-reply-to # header. if self.message: msg = self.message.rfc822() msg = msg.getheader("Message-Id") if msg: mw.addheader("In-Reply-To", msg) # Split the To box into a list of addresses. atfp = cStringIO.StringIO(self.widget.extrasfield.get_chars(0, -1)) while 1: i = atfp.readline() if not i: break i = string.strip(i) header, value = string.split(i, ": ", 1) mw.addheader(header, value) # Do we need to make the body into quoted-printable? body = self.widget.textbox.get_chars(0, -1) if iso_char.search(body): fp = cStringIO.StringIO(body) atfp = cStringIO.StringIO() quopri.encode(fp, atfp, 0) body = atfp.getvalue() bodyencoding = "quoted-printable" else: bodyencoding = "7bit" # Do we have attachments to worry about? if self.widget.attachmentlist.rows: # Yes; we need to send a multipart message. fp = mw.startmultipartbody("mixed") submw = mw.nextpart() submw.addheader("Content-Disposition", "inline; filename=\"body text\"") submw.addheader("Content-Transfer-Encoding", bodyencoding) fp = submw.startbody("text/plain") fp.write(body) for i in xrange(self.widget.attachmentlist.rows): type = self.widget.attachmentlist.get_text(i, 0) name = self.widget.attachmentlist.get_text(i, 2) submw = mw.nextpart() submw.addheader("Content-Disposition", "attachment; filename=\""+name+"\"") # Hack to get around a bug in SpamCop. if (type == "message/rfc822"): submw.addheader("Content-Transfer-Encoding", "8bit") fp = submw.startbody(type) fp.write(self.widget.attachmentlist.get_row_data(i)) else: submw.addheader("Content-Transfer-Encoding", "base64") fp = submw.startbody(type) atfp = cStringIO.StringIO(self.widget.attachmentlist.get_row_data(i)) base64.encode(atfp, fp) mw.lastpart() else: # No; a single part message will do. mw.addheader("Content-Transfer-Encoding", bodyencoding) fp = mw.startbody("text/plain") fp.write(body) return out.getvalue()
"""Various tools used by MIME-reading or MIME-writing programs."""
def quopri_encode(input, errors='strict'): f = StringIO(str(input)) g = StringIO() quopri.encode(f, g, 1) output = g.getvalue() return (output, len(input))
import MimeWriter, quopri, base64, StringIO, sys TEXT = """ here comes the image you asked for. hope it's what you expected. """ FILE = "samples/sample.jpg" file = sys.stdout mime = MimeWriter.MimeWriter(file) mime.addheader("Mime-Version", "1.0") mime.startmultipartbody("mixed") # add a text message part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "quoted-printable") part.startbody("text/plain") quopri.encode(StringIO.StringIO(TEXT), file, 0) # add an image part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "base64") part.startbody("image/jpeg") base64.encode(open(FILE, "rb"), file) mime.lastpart()
#!/usr/bin/env python import getopt import quopri import base64 import sys # QP? Decode? codingfuncs = { (True, True): quopri.decode, (True, False): lambda x, y: quopri.encode(x, y, False), (False, True): base64.decode, (False, False): base64.encode } qp = False decode = False opts, args = getopt.getopt(sys.argv[1:], "qu") for opt, arg in opts: if opt == "-q": qp = True elif opt == "-u": decode = True codingfuncs[(qp, decode)](sys.stdin, sys.stdout)
file = sys.stdout # # create a mime multipart writer instance mime = MimeWriter.MimeWriter(file) mime.addheader("Mime-Version", "1.0") mime.startmultipartbody("mixed") # add a text message # 加入文字信息 part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "quoted-printable") part.startbody("text/plain") quopri.encode(StringIO.StringIO(TEXT), file, 0) # add an image # 加入图片 part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "base64") part.startbody("image/jpeg") base64.encode(open(FILE, "rb"), file) mime.lastpart()
def _quopri_qp(): for data in corpus: data_fh = cStringIO.StringIO(data) out_fh = cStringIO.StringIO() quopri.encode(data_fh, out_fh, False)
def test_encode(self): for p, e in self.STRINGS: infp = cStringIO.StringIO(p) outfp = cStringIO.StringIO() quopri.encode(infp, outfp, quotetabs=False) self.assert_(outfp.getvalue() == e)
def update_event(self, inp=-1): self.set_output_val( 0, quopri.encode(self.input(0), self.input(1), self.input(2), self.input(3)))
def quopri_encode(input, errors='strict'): assert errors == 'strict' f = BytesIO(input) g = BytesIO() quopri.encode(f, g, 1) return (g.getvalue(), len(input))
"""Codec for quoted-printable encoding.
def send_message(self, nodeid, msgid, note, sendto, from_address=None, bcc_sendto=[]): '''Actually send the nominated message from this node to the sendto recipients, with the note appended. ''' users = self.db.user messages = self.db.msg files = self.db.file if msgid is None: inreplyto = None messageid = None else: inreplyto = messages.get(msgid, 'inreplyto') messageid = messages.get(msgid, 'messageid') # make up a messageid if there isn't one (web edit) if not messageid: # this is an old message that didn't get a messageid, so # create one messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(), self.classname, nodeid, self.db.config.MAIL_DOMAIN) if msgid is not None: messages.set(msgid, messageid=messageid) # compose title cn = self.classname title = self.get(nodeid, 'title') or '%s message copy'%cn # figure author information if msgid: authid = messages.get(msgid, 'author') else: authid = self.db.getuid() authname = users.get(authid, 'realname') if not authname: authname = users.get(authid, 'username', '') authaddr = users.get(authid, 'address', '') if authaddr and self.db.config.MAIL_ADD_AUTHOREMAIL: authaddr = " <%s>" % straddr( ('',authaddr) ) elif authaddr: authaddr = "" # make the message body m = [''] # put in roundup's signature if self.db.config.EMAIL_SIGNATURE_POSITION == 'top': m.append(self.email_signature(nodeid, msgid)) # add author information if authid and self.db.config.MAIL_ADD_AUTHORINFO: if msgid and len(self.get(nodeid, 'messages')) == 1: m.append(_("New submission from %(authname)s%(authaddr)s:") % locals()) elif msgid: m.append(_("%(authname)s%(authaddr)s added the comment:") % locals()) else: m.append(_("Change by %(authname)s%(authaddr)s:") % locals()) m.append('') # add the content if msgid is not None: m.append(messages.get(msgid, 'content', '')) # get the files for this message message_files = [] if msgid : for fileid in messages.get(msgid, 'files') : # check the attachment size filename = self.db.filename('file', fileid, None) filesize = os.path.getsize(filename) if filesize <= self.db.config.NOSY_MAX_ATTACHMENT_SIZE: message_files.append(fileid) else: base = self.db.config.TRACKER_WEB link = "".join((base, files.classname, fileid)) filename = files.get(fileid, 'name') m.append(_("File '%(filename)s' not attached - " "you can download it from %(link)s.") % locals()) # add the change note if note: m.append(note) # put in roundup's signature if self.db.config.EMAIL_SIGNATURE_POSITION == 'bottom': m.append(self.email_signature(nodeid, msgid)) # encode the content as quoted-printable charset = getattr(self.db.config, 'EMAIL_CHARSET', 'utf-8') m = '\n'.join(m) if charset != 'utf-8': m = unicode(m, 'utf-8').encode(charset) content = cStringIO.StringIO(m) content_encoded = cStringIO.StringIO() quopri.encode(content, content_encoded, 0) content_encoded = content_encoded.getvalue() # make sure the To line is always the same (for testing mostly) sendto.sort() # make sure we have a from address if from_address is None: from_address = self.db.config.TRACKER_EMAIL # additional bit for after the From: "name" from_tag = getattr(self.db.config, 'EMAIL_FROM_TAG', '') if from_tag: from_tag = ' ' + from_tag subject = '[%s%s] %s'%(cn, nodeid, title) author = (authname + from_tag, from_address) # send an individual message per recipient? if self.db.config.NOSY_EMAIL_SENDING != 'single': sendto = [[address] for address in sendto] else: sendto = [sendto] # now send one or more messages # TODO: I believe we have to create a new message each time as we # can't fiddle the recipients in the message ... worth testing # and/or fixing some day first = True for sendto in sendto: # create the message mailer = Mailer(self.db.config) message, writer = mailer.get_standard_message(sendto, subject, author) # set reply-to to the tracker tracker_name = self.db.config.TRACKER_NAME if charset != 'utf-8': tracker = unicode(tracker_name, 'utf-8').encode(charset) tracker_name = encode_header(tracker_name, charset) writer.addheader('Reply-To', straddr((tracker_name, from_address))) # message ids if messageid: writer.addheader('Message-Id', messageid) if inreplyto: writer.addheader('In-Reply-To', inreplyto) # Generate a header for each link or multilink to # a class that has a name attribute for propname, prop in self.getprops().items(): if not isinstance(prop, (hyperdb.Link, hyperdb.Multilink)): continue cl = self.db.getclass(prop.classname) if not 'name' in cl.getprops(): continue if isinstance(prop, hyperdb.Link): value = self.get(nodeid, propname) if value is None: continue values = [value] else: values = self.get(nodeid, propname) if not values: continue values = [cl.get(v, 'name') for v in values] values = ', '.join(values) writer.addheader("X-Roundup-%s-%s" % (self.classname, propname), values) if not inreplyto: # Default the reply to the first message msgs = self.get(nodeid, 'messages') # Assume messages are sorted by increasing message number here if msgs[0] != nodeid: inreplyto = messages.get(msgs[0], 'messageid') if inreplyto: writer.addheader('In-Reply-To', inreplyto) # attach files if message_files: part = writer.startmultipartbody('mixed') part = writer.nextpart() part.addheader('Content-Transfer-Encoding', 'quoted-printable') body = part.startbody('text/plain; charset=%s'%charset) body.write(content_encoded) for fileid in message_files: name = files.get(fileid, 'name') mime_type = files.get(fileid, 'type') content = files.get(fileid, 'content') part = writer.nextpart() if mime_type == 'text/plain': part.addheader('Content-Disposition', 'attachment;\n filename="%s"'%name) try: content.decode('ascii') except UnicodeError: # the content cannot be 7bit-encoded. # use quoted printable part.addheader('Content-Transfer-Encoding', 'quoted-printable') body = part.startbody('text/plain') body.write(quopri.encodestring(content)) else: part.addheader('Content-Transfer-Encoding', '7bit') body = part.startbody('text/plain') body.write(content) else: # some other type, so encode it if not mime_type: # this should have been done when the file was saved mime_type = mimetypes.guess_type(name)[0] if mime_type is None: mime_type = 'application/octet-stream' part.addheader('Content-Disposition', 'attachment;\n filename="%s"'%name) part.addheader('Content-Transfer-Encoding', 'base64') body = part.startbody(mime_type) body.write(base64.encodestring(content)) writer.lastpart() else: writer.addheader('Content-Transfer-Encoding', 'quoted-printable') body = writer.startbody('text/plain; charset=%s'%charset) body.write(content_encoded) if first: mailer.smtp_send(sendto + bcc_sendto, message) else: mailer.smtp_send(sendto, message) first = False
def encodestring(instring, tabs=0): outfile = io.BytesIO() quopri.encode(io.BytesIO(instring.encode()), outfile, tabs) return outfile.getvalue().decode("utf-8", "ignore")
def makemessage(self, tofield=None): if not tofield: tofield = self.widget.tofield.get_text() out = cStringIO.StringIO() mw = MimeWriter.MimeWriter(out) # Write standard header. mw.addheader("X-Mailer", "SQmaiL (http://sqmail.sourceforge.net)") mw.addheader("From", self.widget.fromfield.get_text()) mw.addheader("To", tofield) mw.addheader("Subject", self.widget.subjectfield.get_text()) mw.addheader("MIME-Version", "1.0") # Send the X-Face? if sqmail.preferences.get_sendxface(): mw.addheader("X-Face", sqmail.preferences.get_outgoingxfaceicon()) # If we were replying to something, write the in-reply-to # header. if self.message: msg = self.message.rfc822() msg = msg.getheader("Message-Id") if msg: mw.addheader("In-Reply-To", msg) # Split the To box into a list of addresses. atfp = cStringIO.StringIO(self.widget.extrasfield.get_chars(0, -1)) while 1: i = atfp.readline() if not i: break i = string.strip(i) header, value = string.split(i, ": ", 1) mw.addheader(header, value) # Do we need to make the body into quoted-printable? body = self.widget.textbox.get_chars(0, -1) if iso_char.search(body): fp = cStringIO.StringIO(body) atfp = cStringIO.StringIO() quopri.encode(fp, atfp, 0) body = atfp.getvalue() bodyencoding = "quoted-printable" else: bodyencoding = "7bit" # Do we have attachments to worry about? if self.widget.attachmentlist.rows: # Yes; we need to send a multipart message. fp = mw.startmultipartbody("mixed") submw = mw.nextpart() submw.addheader("Content-Disposition", "inline; filename=\"body text\"") submw.addheader("Content-Transfer-Encoding", bodyencoding) fp = submw.startbody("text/plain") fp.write(body) for i in xrange(self.widget.attachmentlist.rows): type = self.widget.attachmentlist.get_text(i, 0) name = self.widget.attachmentlist.get_text(i, 2) submw = mw.nextpart() submw.addheader("Content-Disposition", "attachment; filename=\"" + name + "\"") # Hack to get around a bug in SpamCop. if (type == "message/rfc822"): submw.addheader("Content-Transfer-Encoding", "8bit") fp = submw.startbody(type) fp.write(self.widget.attachmentlist.get_row_data(i)) else: submw.addheader("Content-Transfer-Encoding", "base64") fp = submw.startbody(type) atfp = cStringIO.StringIO( self.widget.attachmentlist.get_row_data(i)) base64.encode(atfp, fp) mw.lastpart() else: # No; a single part message will do. mw.addheader("Content-Transfer-Encoding", bodyencoding) fp = mw.startbody("text/plain") fp.write(body) return out.getvalue()
def send_email(dirname, to, from_): #def sendmail( filenames,to,from_,subject,body="",mysmtp = 'localhost'): import email, email.Utils, types, os, os.path, mimetypes, string, \ time, smtplib, logging, exceptions,fcntl,sys,shutil,email.MIMEBase,email.MIMEText filenames = [dirname+'_nmag4_M.dat',dirname+'_results.png',\ dirname+'_results.eps.gz'] mysmtp = emailSMTP subject = "nmag test results " + dirname attempt('cat ' + deviationlogfilenmag20070328 + ' | tail -n 20 > nmag3deviationtail.txt') attempt('cat ' + deviationlogfileoommf + ' | tail -n 20 > oommfdeviationtail.txt') body1 = open(dirname + '_info.txt', 'r').read() body2 = open('nmag3deviationtail.txt', 'r').read() body3 = open('oommfdeviationtail.txt', 'r').read() body4 = open('bigbar_timings.log').read()[-3200:] body = body1 + '\n---Deviation to nmag3 ---------------\n' + body2 body += '\n---Deviation to OOMMF ---------------\n' + body3 body += '\n---timings ---------------\n' + body4 body += 'host rev date sim init writing-data sim&write total' attempt('rm -f nmag3deviationtail.txt') attempt('rm -f oommfdeviationtail.txt') log_global = logging """bundle all files given in list of filenames This is taken from Matthew Cowles http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86674 (which guess the file type of the attachements) with modification for attaching body from http://snippets.dzone.com/posts/show/757 Could do with some tidying up (fangohr 27/03/2007) """ if type(to) != types.ListType: raise TypeError, "Can't handle type %s for 'to' (needs to be a list)" % type( to) import cStringIO import base64 import email.Generator import email.Message import mimetypes import os import quopri mainMsg = email.Message.Message() #mainMsg["To"]=' '.join(to) from email.Utils import COMMASPACE, formatdate mainMsg["To"] = COMMASPACE.join(to) mainMsg["From"] = from_ mainMsg["Subject"] = subject mainMsg["Mime-version"] = "1.0" mainMsg["Content-type"] = "Multipart/mixed" mainMsg.preamble = "Mime message\n" + body mainMsg.epilogue = "" # To ensure that message ends with newline mainMsg.attach(email.MIMEText.MIMEText(body)) # try to attach body # Get names of plain files for fileName in filenames: print "working on", fileName contentType, ignored = mimetypes.guess_type(fileName) if contentType == None: # If no guess, use generic opaque type contentType = "application/octet-stream" contentsEncoded = cStringIO.StringIO() f = open(fileName, "rb") mainType = contentType[:contentType.find("/")] if mainType == "text": cte = "quoted-printable" quopri.encode(f, contentsEncoded, 1) # 1 for encode tabs else: cte = "base64" base64.encode(f, contentsEncoded) f.close() subMsg = email.Message.Message() subMsg.add_header("Content-type", contentType, name=fileName) subMsg.add_header("Content-transfer-encoding", cte) subMsg.set_payload(contentsEncoded.getvalue()) contentsEncoded.close() mainMsg.attach(subMsg) msg = mainMsg fromAddr = from_ toAddr = to assert fromAddr, "No from-addr given: %s" % (fromAddr) assert toAddr, "No to-addr given: %s" % (toAddr) log_global.info("sending email from %s to %s" % (fromAddr, toAddr)) log_global.info("(deliver email to %s via smtp to %s)" % (toAddr, mysmtp)) import socket smtp = smtplib.SMTP(mysmtp) smtp.set_debuglevel(0) #put in 1 for messages to stdout/stderr smtp.sendmail(fromAddr, to, msg.as_string()) smtp.quit() log_global.debug("finished sending email to %s" % (toAddr))
def encode_quoted_printable(infile, outfile): quopri.encode(infile, outfile, 0)
#!/usr/bin/env python import getopt import quopri import base64 import sys # QP? Decode? codingfuncs = {(True, True): quopri.decode, (True, False): lambda x,y: quopri.encode(x,y,False), (False, True): base64.decode, (False, False): base64.encode} qp = False decode = False opts, args = getopt.getopt(sys.argv[1:], "qu") for opt, arg in opts: if opt == "-q": qp = True elif opt == "-u": decode = True codingfuncs[(qp, decode)](sys.stdin, sys.stdout)
def encodestring(instring, tabs = 0): outfile = io.StringIO() print(io.StringIO(instring),type(io.StringIO(instring))) print(outfile,type(outfile)) quopri.encode(io.StringIO(instring), outfile, tabs) return outfile.getvalue()
def quopri_encode(input, errors='strict'): f = BytesIO(input) g = BytesIO() quopri.encode(f, g, 1) return (g.getvalue(), len(input))