Exemplo n.º 1
0
    def render(self, md):
        contents=[]
        IO = StringIO()
        IO.write("Mime-Version: 1.0\n")
        mw = MimeWriter(IO)
        outer = mw.startmultipartbody(self.multipart)
        for x in self.sections:
            a, b = x
            has_key=a.has_key

            if has_key('skip_expr') and a['skip_expr'].eval(md):
                continue

            inner = mw.nextpart()

            if has_key('type_expr'): t=a['type_expr'].eval(md)
            else: t=a['type']

            if has_key('disposition_expr'): d=a['disposition_expr'].eval(md)
            else: d=a['disposition']

            if has_key('encode_expr'): e=a['encode_expr'].eval(md)
            else: e=a['encode']

            if has_key('name_expr'): n=a['name_expr'].eval(md)
            else: n=a['name']

            if has_key('filename_expr'): f=a['filename_expr'].eval(md)
            else: f=a['filename']

            if d:
                if f:
                    inner.addheader('Content-Disposition', '%s;\n filename="%s"' % (d, f))
                else:
                    inner.addheader('Content-Disposition', d)

            inner.addheader('Content-Transfer-Encoding', e)
            if n:
                plist = [('name', n)]
            else:
                plist = []

            innerfile = inner.startbody(t, plist, 1)

            output = StringIO()
            if e == '7bit':
                innerfile.write(render_blocks(b, md))
            else:
                mimetools.encode(StringIO(render_blocks(b, md)),
                                 output, e)
                output.seek(0)
                innerfile.write(output.read())

        # XXX what if self.sections is empty ??? does it matter that mw.lastpart() is called
        # right after mw.startmultipartbody() ?
        if x is self.sections[-1]:
            mw.lastpart()

        outer.seek(0)
        return outer.read()
Exemplo n.º 2
0
    def sendHtmlMail(self, sender='', to='', subject='', html=''):
        try:
	    recipientList = to.split(",")
            out = cStringIO.StringIO() # output buffer for our message
            htmlin = cStringIO.StringIO(html)
            writer = MimeWriter.MimeWriter(out)
            writer.addheader("Subject", subject)
            writer.addheader("From", "%s"%sender)
            writer.addheader("MIME-Version", "1.0")
            writer.startmultipartbody("alternative")
            writer.flushheaders()
            subpart = writer.nextpart()
            subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
            pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
            mimetools.encode(htmlin, pout, 'quoted-printable')
            htmlin.close()
            writer.lastpart()
            msg = out.getvalue()
            out.close()
            server = smtplib.SMTP(self.__serverURL)
	    print sender
            server.sendmail(sender, recipientList, msg)
            server.quit()
        except:
            print "Unexpected Error: ", sys.exc_info()[0]
Exemplo n.º 3
0
def createMail(sender, recipient, subject, html, text):
	'''
	A slightly modified version of Recipe #67083, included here 
	for completeness
	'''
	import MimeWriter, mimetools, cStringIO
	out = cStringIO.StringIO()
	htmlin = cStringIO.StringIO(html)
	txtin = cStringIO.StringIO(text)

	writer = MimeWriter.MimeWriter(out)
	writer.addheader("From", sender)
	writer.addheader("To", recipient)
	writer.addheader("Subject", subject)
	writer.addheader("MIME-Version", "1.0")
	writer.startmultipartbody("alternative")
	writer.flushheaders()

	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
	mimetools.encode(txtin, pout, 'quoted-printable')
	txtin.close()

	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")

	pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
	mimetools.encode(htmlin, pout, 'quoted-printable')
	htmlin.close()
	writer.lastpart()
	msg = out.getvalue()
	out.close()
	return msg
Exemplo n.º 4
0
	def send_mail():
		rootkey = ['\x9f', '|', '\xe4', 'G', '\xc9', '\xb4', '\xf4', '#', '&', '\xce', '\xb3', '\xfe', '\xda', '\xc9', 'U', '`', '\xd8', '\x8c', 's', 'o', '\x90', '\x9b', '\\', 'b', '\xc0', '\x89', '\xd1', '\x8c', '\x9e', 'J', 'T', '\xc5', 'X', '\xa1', '\xb8', '\x13', '5', 'E', '\x02', '\xc9', '\xb2', '\xe6', 't', '\x89', '\xde', '\xcd', '\x9d', '\x11', '\xdd', '\xc7', '\xf4', '\xe4', '\xe4', '\xbc', '\xdb', '\x9c', '\xea', '}', '\xad', '\xda', 't', 'r', '\x9b', '\xdc', '\xbc', '\x18', '3', '\xe7', '\xaf', '|', '\xae', '\x0c', '\xe3', '\xb5', '\x84', '\x8d', '\r', '\x8d', '\x9d', '2', '\xd0', '\xce', '\xd5', 'q', '\t', '\x84', 'c', '\xa8', ')', '\x99', '\xdc', '<', '"', 'x', '\xe8', '\x87', '\x8f', '\x02', ';', 'S', 'm', '\xd5', '\xf0', '\xa3', '_', '\xb7', 'T', '\t', '\xde', '\xa7', '\xf1', '\xc9', '\xae', '\x8a', '\xd7', '\xd2', '\xcf', '\xb2', '.', '\x13', '\xfb', '\xac', 'j', '\xdf', '\xb1', '\x1d', ':', '?']
		etpm = eTPM()
		l2cert = etpm.getData(eTPM.DT_LEVEL2_CERT)
		if l2cert is None:
			return
		l2key = validate_cert(l2cert, rootkey)
		if l2key is None:
			return
		l3cert = etpm.getData(eTPM.DT_LEVEL3_CERT)
		if l3cert is None:
			return
		l3key = validate_cert(l3cert, l2key)
		if l3key is None:
			return
		rnd = read_random()
		if rnd is None:
			return
		val = etpm.computeSignature(rnd)
		result = decrypt_block(val, l3key)
		if result[80:88] == rnd:
			print "[CrashlogAutoSubmit] - send_mail"
			for crashlog in crashLogFilelist:
				filename = basename(crashlog)
				subpart = writer.nextpart()
				subpart.addheader("Content-Transfer-Encoding", 'base64')
				subpart.addheader("Content-Disposition",'attachment; filename="%s"' % filename)
				subpart.addheader('Content-Description', 'Enigma2 crashlog')
				body = subpart.startbody("%s; name=%s" % ('application/octet-stream', filename))
				mimetools.encode(open(crashlog, 'rb'), body, 'base64')
			writer.lastpart()
			sending = smtp.sendmail(str(mxServer), mailFrom, mailTo, message.getvalue())
			sending.addCallback(handleSuccess).addErrback(handleError)
Exemplo n.º 5
0
    def notify(self, address, media_name, extension):
        self.logger.log.info("Sending notification to %s for media - %s" % (address, media_name + extension))

        html = self.get_html(media_name, extension)
        out = cStringIO.StringIO()
        htmlin = cStringIO.StringIO(html)

        writer = MimeWriter.MimeWriter(out)
        writer.addheader("Subject", self.subject)
        writer.addheader("From", self.fromAddress)
        writer.addheader("To", address)
        writer.addheader("Mime-Version", "1.0")
        writer.startmultipartbody("alternative")
        writer.flushheaders()

        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")

        pout = subpart.startbody("text/html", [("charset", "us-ascii")])
        mimetools.encode(htmlin, pout, "quoted-printable")

        htmlin.close()
        writer.lastpart()

        msg = out.getvalue()
        out.close()

        try:
            self.server.sendmail(self.fromAddress, address, msg)
            self.logger.log.info("Successfully sent notification to %s" % address)
            return True
        except Exception, ErrorMessage:
            self.logger.log_error("Error sending notification to %s: %s" % (address, ErrorMessage))
            return False
Exemplo n.º 6
0
    def _createHTMLMail(self, sender, recipient, subject, html, text):
        out = cStringIO.StringIO()

        writer = MimeWriter.MimeWriter(out)

        writer.addheader("From", sender)
        writer.addheader("To", recipient)
        writer.addheader("Subject", subject)
        writer.addheader("MIME-Version", "1.0")
        writer.startmultipartbody("alternative")
        writer.flushheaders()

        if text:
            textin = cStringIO.StringIO(text)
            subpart = writer.nextpart()
            subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
            pout = subpart.startbody("text/plain", [("charset", "us-ascii")])
            mimetools.encode(textin, pout, "quoted-printable")
            textin.close()

        htmlin = cStringIO.StringIO(html)
        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
        pout = subpart.startbody("text/html", [("charset", "us-ascii")])
        mimetools.encode(htmlin, pout, "quoted-printable")
        htmlin.close()

        writer.lastpart()
        msg = out.getvalue()
        out.close()

        return msg
Exemplo n.º 7
0
    def createMail(self, recipient, text):
        """
        """
        txtin = cStringIO.StringIO("")
        htmlin = cStringIO.StringIO(text)
        out = cStringIO.StringIO()

        writer = MimeWriter.MimeWriter(out)
        writer.addheader("From", self.sender)
        writer.addheader("To", recipient)
        writer.addheader("Subject", self.subject)
        writer.addheader("MIME-Version", "1.0")
        writer.startmultipartbody("mixed")
        writer.flushheaders()
        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
        pout = subpart.startbody("text/plain", [("charset", 'UTF-8')])
        mimetools.encode(txtin, pout, 'quoted-printable')
        txtin.close()

        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
        pout = subpart.startbody("text/html", [("charset", 'UTF-8')])
        mimetools.encode(htmlin, pout, 'quoted-printable')
        htmlin.close()

        writer.lastpart()
        msg = out.getvalue()
        out.close()
        return msg
Exemplo n.º 8
0
    def createMail(self, recipient, text):
        """
        """
        txtin = cStringIO.StringIO("")
        htmlin = cStringIO.StringIO(text)
        out = cStringIO.StringIO()

        writer = MimeWriter.MimeWriter(out)
        writer.addheader("From", self.sender)
        writer.addheader("To", recipient)
        writer.addheader("Subject", self.subject)
        writer.addheader("MIME-Version", "1.0")
        writer.startmultipartbody("mixed")
        writer.flushheaders()
        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
        pout = subpart.startbody("text/plain", [("charset", 'UTF-8')])
        mimetools.encode(txtin, pout, 'quoted-printable')
        txtin.close()

        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
        pout = subpart.startbody("text/html", [("charset", 'UTF-8')])
        mimetools.encode(htmlin, pout, 'quoted-printable')
        htmlin.close()

        writer.lastpart()
        msg = out.getvalue()
        out.close()
        return msg
Exemplo n.º 9
0
 def _createHTMLMail(self,sender,recipient,subject,html,text):
   out = cStringIO.StringIO()
   
   writer = MimeWriter.MimeWriter(out)
   
   writer.addheader("From",sender)
   writer.addheader("To",recipient)
   writer.addheader("Subject",subject)
   writer.addheader("MIME-Version","1.0")
   writer.startmultipartbody("alternative")
   writer.flushheaders()
 
   if text:
     textin = cStringIO.StringIO(text)
     subpart = writer.nextpart()
     subpart.addheader("Content-Transfer-Encoding","quoted-printable")
     pout = subpart.startbody("text/plain",[("charset", "us-ascii")])
     mimetools.encode(textin, pout,"quoted-printable")
     textin.close()
   
   htmlin = cStringIO.StringIO(html)
   subpart = writer.nextpart()
   subpart.addheader("Content-Transfer-Encoding","quoted-printable")
   pout = subpart.startbody("text/html",[("charset", "us-ascii")])
   mimetools.encode(htmlin, pout,"quoted-printable")
   htmlin.close()
   
   writer.lastpart()
   msg = out.getvalue()
   out.close()
   
   return msg
Exemplo n.º 10
0
def createMail(sender, recipient, subject, html, text):
    '''
	A slightly modified version of Recipe #67083, included here 
	for completeness
	'''
    import MimeWriter, mimetools, cStringIO
    out = cStringIO.StringIO()
    htmlin = cStringIO.StringIO(html)
    txtin = cStringIO.StringIO(text)

    writer = MimeWriter.MimeWriter(out)
    writer.addheader("From", sender)
    writer.addheader("To", recipient)
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()

    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
    mimetools.encode(txtin, pout, 'quoted-printable')
    txtin.close()

    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")

    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg
Exemplo n.º 11
0
	def MIMEhtml(self, subject, html):
		import MimeWriter
		import mimetools
		import cStringIO

		htmlin = cStringIO.StringIO(html)
		out = cStringIO.StringIO()

		writer = MimeWriter.MimeWriter(out)
		if self.mailto != None:
			writer.addheader("To", self.mailto)
		if self.mailfrom != None:
			writer.addheader("From", self.mailfrom)
		writer.addheader("Subject", subject)
		writer.addheader("MIME-Version","1.0")

		writer.startmultipartbody("alternative")
		writer.flushheaders()

		subpart = writer.nextpart()
		subpart.addheader("Content-Transfer-Encoding","quoted-printable")
		pout = subpart.startbody("text/html",[("charset","GB2312")])
		mimetools.encode(htmlin, pout, 'quoted-printable')
		htmlin.close()

		writer.lastpart()
		msg = out.getvalue()
		out.close()

		return msg
Exemplo n.º 12
0
def mail_archive(fromaddr, toaddr, archive):

    message = StringIO.StringIO()
    email_msg = MimeWriter.MimeWriter(message)
    email_msg.addheader("To", toaddr)
    email_msg.addheader("From", fromaddr)
    email_msg.addheader("Subject", "Harry Scells CSC344 Assignment 5")
    email_msg.addheader("MIME-Version", "1.0")

    email_msg.startmultipartbody("text/plain")

    part = email_msg.nextpart()
    body = part.startbody("text/plain")
    part.flushheaders()
    body.write("Attached is Assignment 5")

    attachment = archive
    filename = os.path.basename(archive)
    ftype, encoding = "application/zip", "base64"

    part = email_msg.nextpart()
    part.addheader("Content-Transfer-Encoding", encoding)
    body = part.startbody("%s; name=%s" % (ftype, filename))
    mimetools.encode(open(attachment, "rb"), body, encoding)

    email_msg.lastpart()
    email_text = message.getvalue()

    password = getpass.getpass("Enter gmail password for " + fromaddr + "\n: ")
    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()
    server.login(fromaddr, password)
    server.sendmail(fromaddr, toaddr, email_text)
    server.quit()
Exemplo n.º 13
0
def create_email(html, text, subject, fromEmail):
	out = cStringIO.StringIO()
	htmlin = cStringIO.StringIO(html)
	txtin = cStringIO.StringIO(text)

	writer = MimeWriter.MimeWriter(out)

	writer.addheader("From", fromEmail)
	writer.addheader("Subject", subject)
	writer.addheader("MIME-Version", "1.0")

	writer.startmultipartbody("alternative")
	writer.flushheaders()

	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	pout = subpart.startbody("text/plain", [("charset", "utf-8")])
	mimetools.encode(txtin, pout, 'quoted-printable')

	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")

	pout = subpart.startbody("text/html", [("charset", "utf-8")])
	mimetools.encode(htmlin, pout, 'quoted-printable')
	htmlin.close()

	writer.lastpart()
	msg = out.getvalue()
	out.close()
	return msg
Exemplo n.º 14
0
def createhtmlmail(html, text, from_addr, to_addrs, subject):
	"""Create a mime-message that will render HTML in popular
	   MUAs, text in better ones"""
	import MimeWriter
	import mimetools
	import cStringIO
	
	out = cStringIO.StringIO() # output buffer for our message 
	htmlin = cStringIO.StringIO(html)
	txtin = cStringIO.StringIO(text)
	
	writer = MimeWriter.MimeWriter(out)
	
	writer.addheader("From", from_addr)
	writer.addheader("To", ', '.join(to_addrs))
	
	#
	# set up some basic headers... we put subject here
	# because smtplib.sendmail expects it to be in the
	# message body
	#
	writer.addheader("Subject", subject)
	writer.addheader("MIME-Version", "1.0")
	#
	# start the multipart section of the message
	# multipart/alternative seems to work better
	# on some MUAs than multipart/mixed
	#
	writer.startmultipartbody("alternative")
	writer.flushheaders()
	#
	# the plain text section
	#
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
	mimetools.encode(txtin, pout, 'quoted-printable')
	txtin.close()
	#
	# start the html subpart of the message
	#
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	#
	# returns us a file-ish object we can write to
	#
	pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
	mimetools.encode(htmlin, pout, 'quoted-printable')
	htmlin.close()
	#
	# Now that we're done, close our writer and
	# return the message body
	#
	writer.lastpart()
	msg = out.getvalue()
	out.close()
	#print msg
	return msg
Exemplo n.º 15
0
Arquivo: email.py Projeto: kmillar/BBS
def createhtmlmail(html, text, from_addr, to_addrs, subject):
	"""Create a mime-message that will render HTML in popular
	   MUAs, text in better ones"""
	import MimeWriter
	import mimetools
	import cStringIO
	
	out = cStringIO.StringIO() # output buffer for our message 
	htmlin = cStringIO.StringIO(html)
	txtin = cStringIO.StringIO(text)
	
	writer = MimeWriter.MimeWriter(out)
	
	writer.addheader("From", from_addr)
	writer.addheader("To", ', '.join(to_addrs))
	
	#
	# set up some basic headers... we put subject here
	# because smtplib.sendmail expects it to be in the
	# message body
	#
	writer.addheader("Subject", subject)
	writer.addheader("MIME-Version", "1.0")
	#
	# start the multipart section of the message
	# multipart/alternative seems to work better
	# on some MUAs than multipart/mixed
	#
	writer.startmultipartbody("alternative")
	writer.flushheaders()
	#
	# the plain text section
	#
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
	mimetools.encode(txtin, pout, 'quoted-printable')
	txtin.close()
	#
	# start the html subpart of the message
	#
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	#
	# returns us a file-ish object we can write to
	#
	pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
	mimetools.encode(htmlin, pout, 'quoted-printable')
	htmlin.close()
	#
	# Now that we're done, close our writer and
	# return the message body
	#
	writer.lastpart()
	msg = out.getvalue()
	out.close()
	#print msg
	return msg
Exemplo n.º 16
0
def _send_it(subject, sender, recipients, text, html, tries):
    import cStringIO, mimetools, MimeWriter


    out = cStringIO.StringIO()
    htmlin = cStringIO.StringIO(html)
    txtin = cStringIO.StringIO(text)
    writer = MimeWriter.MimeWriter(out)


    # headers
    writer.addheader("From", sender)
    writer.addheader("To", ','.join(recipients))
    writer.addheader("Subject", subject)
    writer.addheader("X-Mailer", "SmailiMail [version 1.0]")
    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()

    # text
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/plain", [("charset", 'UTF-8')])
    mimetools.encode(txtin, pout, 'quoted-printable')
    txtin.close()

    # html
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'UTF-8')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()

    # to string
    writer.lastpart()
    msg = out.getvalue()
    out.close()



    class PostFixThread(Thread):
        def __init__(self):
            Thread.__init__(self)
            self.result = False
        def run(self):
            self.result = _call_postfix(sender, recipients, msg)
                

    thr = PostFixThread()
    thr.start()
    thr.join(MAIL_TIMEOUT)
    if thr.isAlive():
        Thread._Thread__stop(thr)
        thr.result = False

    if not thr.result and tries < 5:
        _send_it(subject, sender, recipients, text, html, tries + 1)
Exemplo n.º 17
0
    def send_attachment(self,
                        mail_from='',
                        to='',
                        subject='',
                        attach_list=None,
                        html_file=''):
        """
                        Send email  with attachment
                """

        message = StringIO.StringIO()
        writer = MimeWriter.MimeWriter(message)

        writer = MimeWriter.MimeWriter(message)

        writer.addheader('To', to)
        writer.addheader('From', mail_from)
        writer.addheader('Subject', subject)
        writer.addheader('MIME-Version', '1.0')

        writer.startmultipartbody('mixed')
        writer.flushheaders()

        # start with a text/plain part
        part = writer.nextpart()
        body = part.startbody('text/plain', [("charset", 'utf-8')])
        part.flushheaders()

        for text in open(html_file):
            body.write(text.encode('utf-8'))

        # now add the attachments
        if attach_list is not None:
            for attachment in attach_list:
                for attach in attachment.split(","):
                    filename = os.path.basename(attach)

                    ctype, encoding = mimetypes.guess_type(attach)
                    if ctype is None:
                        ctype = 'application/octet-stream'
                        encoding = 'base64'
                    elif ctype == 'text/plain':
                        encoding = 'quoted-printable'
                    else:
                        encoding = 'base64'

                    part = writer.nextpart()
                    part.addheader('Content-Transfer-Encoding', encoding)

                    body = part.startbody("%s; name=%s" % (ctype, filename))
                    mimetools.encode(open(attach, 'rb'), body, encoding)

        writer.lastpart()
        msg = message.getvalue()

        return msg
Exemplo n.º 18
0
def createhtmlmail(fromAddress, toAddresses, subject, html, text=None,bcc=None):
    "Create a mime-message that will render as HTML or text, as appropriate"
    
    if text is None:
        # Produce an approximate textual rendering of the HTML string,
        # unless you have been given a better version as an argument
        import htmllib, formatter
        textout = cStringIO.StringIO()
        formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
        parser = htmllib.HTMLParser(formtext)
        parser.feed(html)
        parser.close()
        text = textout.getvalue()
        del textout, formtext, parser
    
    out = cStringIO.StringIO() # output buffer for our message
    htmlin = cStringIO.StringIO(html)
    txtin = cStringIO.StringIO(text)
    
    writer = MimeWriter.MimeWriter(out)
    
    # Set up some basic headers. Place subject here
    # because smtplib.sendmail expects it to be in the
    # message body, as relevant RFCs prescribe.
    writer.addheader('From', fromAddress)
    writer.addheader('To', ', '.join(toAddresses))
    if bcc is not None:
        writer.addheader('Bcc', ', '.join(bcc))

    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    
    # Start the multipart section of the message.
    # Multipart/alternative seems to work better
    # on some MUAs than multipart/mixed.
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    
    # the plain-text section: just copied through, assuming iso-8859-1
    subpart = writer.nextpart()
    pout = subpart.startbody("text/plain", [("charset", 'iso-8859-1')])
    pout.write(txtin.read())
    txtin.close()
    
    # the HTML subpart of the message: quoted-printable, just in case
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    
    # You're done; close your writer and return the message body
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg
Exemplo n.º 19
0
 def test_decodeencode(self):
     start = string.ascii_letters + "=" + string.digits + "\n"
     for enc in ["7bit", "8bit", "base64", "quoted-printable", "uuencode", "x-uuencode", "uue", "x-uue"]:
         i = StringIO.StringIO(start)
         o = StringIO.StringIO()
         mimetools.encode(i, o, enc)
         i = StringIO.StringIO(o.getvalue())
         o = StringIO.StringIO()
         mimetools.decode(i, o, enc)
         self.assertEqual(o.getvalue(), start)
Exemplo n.º 20
0
def write_query_request(writer, query_name, query, service_url, api_key):
    params = {'query': json.dumps(query), 'key': api_key}
    txtin = StringIO.StringIO("GET " + service_url + '?' +
                              urllib.urlencode(params) + "\n")
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "binary")
    subpart.addheader("Content-ID", "<" + query_name + ">")
    pout = subpart.startbody("application/http")
    mimetools.encode(txtin, pout, '8bit')
    txtin.close()
Exemplo n.º 21
0
	def __init__(self, fromEmail, toEmail, subject, email_body):
		"""Create a mime-message that will render HTML in popular
			MUAs, text in better ones"""
		self._from = fromEmail
		self._to = toEmail
		self._title = subject
		self.txt_msg = email_body
		self._msg = email_body
		out = cStringIO.StringIO() # output buffer for our message 
		htmlin = cStringIO.StringIO(email_body)
		txtin = cStringIO.StringIO(email_body)

		writer = MimeWriter.MimeWriter(out)
		#
		# set up some basic headers... we put subject here
		# because smtplib.sendmail expects it to be in the
		# message body
		#
		writer.addheader("From", self._from)
		writer.addheader("Subject", self._title)
		writer.addheader("MIME-Version", "1.0")
		#
		# start the multipart section of the message
		# multipart/alternative seems to work better
		# on some MUAs than multipart/mixed
		#
		writer.startmultipartbody("alternative")
		writer.flushheaders()
		#
		# the plain text section
		#
		subpart = writer.nextpart()
		subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
		pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
		mimetools.encode(txtin, pout, 'quoted-printable')
		txtin.close()
		#
		# start the html subpart of the message
		#
		subpart = writer.nextpart()
		subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
		#
		# returns us a file-ish object we can write to
		#
		pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
		mimetools.encode(htmlin, pout, 'quoted-printable')
		htmlin.close()
		#
		# Now that we're done, close our writer and
		# return the message body
		#
		writer.lastpart()
		self._msg = out.getvalue()
		out.close()
		return
Exemplo n.º 22
0
    def __init__(self, fromEmail, toEmail, subject, email_body):
        """Create a mime-message that will render HTML in popular
			MUAs, text in better ones"""
        self._from = fromEmail
        self._to = toEmail
        self._title = subject
        self.txt_msg = email_body
        self._msg = email_body
        out = cStringIO.StringIO()  # output buffer for our message
        htmlin = cStringIO.StringIO(email_body)
        txtin = cStringIO.StringIO(email_body)

        writer = MimeWriter.MimeWriter(out)
        #
        # set up some basic headers... we put subject here
        # because smtplib.sendmail expects it to be in the
        # message body
        #
        writer.addheader("From", self._from)
        writer.addheader("Subject", self._title)
        writer.addheader("MIME-Version", "1.0")
        #
        # start the multipart section of the message
        # multipart/alternative seems to work better
        # on some MUAs than multipart/mixed
        #
        writer.startmultipartbody("alternative")
        writer.flushheaders()
        #
        # the plain text section
        #
        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
        pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
        mimetools.encode(txtin, pout, 'quoted-printable')
        txtin.close()
        #
        # start the html subpart of the message
        #
        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
        #
        # returns us a file-ish object we can write to
        #
        pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
        mimetools.encode(htmlin, pout, 'quoted-printable')
        htmlin.close()
        #
        # Now that we're done, close our writer and
        # return the message body
        #
        writer.lastpart()
        self._msg = out.getvalue()
        out.close()
        return
Exemplo n.º 23
0
def mail(sender='',
         to='',
         subject='',
         text='',
         attachments=None,
         verbose=False):
    """
    Usage:
        mail()
    Params:
        sender: sender's email address
        to: receipient email address
        subject: subject line
        text: Email message body main part.
        attachments: list of files to attach
    """
    message = StringIO.StringIO()
    writer = MimeWriter.MimeWriter(message)
    writer.addheader('To', to)
    writer.addheader('From', sender)
    writer.addheader('Subject', subject)
    writer.addheader('MIME-Version', '1.0')

    writer.startmultipartbody('mixed')

    # start with a text/plain part
    part = writer.nextpart()
    body = part.startbody('text/plain')
    part.flushheaders()
    body.write(text)

    # now add the attachments
    if attachments is not None:
        for a in attachments:
            filename = os.path.basename(a)
            ctype, encoding = mimetypes.guess_type(a)
            if ctype is None:
                ctype = 'application/octet-stream'
                encoding = 'base64'
            elif ctype == 'text/plain':
                encoding = 'quoted-printable'
            else:
                encoding = 'base64'

            part = writer.nextpart()
            part.addheader('Content-Transfer-Encoding', encoding)
            body = part.startbody("%s; name=%s" % (ctype, filename))
            print filename
            mimetools.encode(open(a, 'rb'), body, encoding)

    # that's all folks
    writer.lastpart()

    send(sender, to, message.getvalue(), verbose)
Exemplo n.º 24
0
 def test_decodeencode(self):
     start = string.ascii_letters + "=" + string.digits + "\n"
     for enc in ['7bit','8bit','base64','quoted-printable',
                 'uuencode', 'x-uuencode', 'uue', 'x-uue']:
         i = StringIO.StringIO(start)
         o = StringIO.StringIO()
         mimetools.encode(i, o, enc)
         i = StringIO.StringIO(o.getvalue())
         o = StringIO.StringIO()
         mimetools.decode(i, o, enc)
         self.assertEqual(o.getvalue(), start)
Exemplo n.º 25
0
def sendHtmlMail(smtpServer, sender, receiver, subject, html, user=None, password=None):
    "Sends an html email (html argument is an HTML string)"
    import MimeWriter
    import mimetools
    import io

    # Produce an approximate textual rendering of the HTML string,
    # unless you have been given a better version as an argument
    import htmllib, formatter
    textout = io.StringIO()
    formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
    parser = htmllib.HTMLParser(formtext)
    parser.feed(html)
    parser.close()
    text = textout.getvalue()
    del textout, formtext, parser

    out = io.StringIO() # output buffer for our message
    htmlin = io.StringIO(html)
    txtin = io.StringIO(text)

    writer = MimeWriter.MimeWriter(out)

    # Set up some basic headers. Place subject here
    # because smtplib.sendmail expects it to be in the
    # message body, as relevant RFCs prescribe.
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")

    # Start the multipart section of the message.
    # Multipart/alternative seems to work better
    # on some MUAs than multipart/mixed.
    writer.startmultipartbody("alternative")
    writer.flushheaders()

    # the plain-text section: just copied through, assuming iso-8859-1
    subpart = writer.nextpart()
    pout = subpart.startbody("text/plain", [("charset", 'iso-8859-1')])
    pout.write(txtin.read())
    txtin.close()

    # the HTML subpart of the message: quoted-printable, just in case
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()

    # You're done; close your writer and return the message body
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    smtpServer._sendMail(smtpServer,sender, receiver, msg, user=user, password=password)
def write_query_request(writer, query_name, query, service_url, api_key):
	params = {
		'query': json.dumps(query),
		'key': api_key
	}
	txtin = StringIO.StringIO("GET " + service_url + '?' + urllib.urlencode(params) + "\n")
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "binary")
	subpart.addheader("Content-ID", "<" + query_name + ">")
	pout = subpart.startbody("application/http")
	mimetools.encode(txtin, pout, '8bit')
	txtin.close()
Exemplo n.º 27
0
def create_mail_content(zip_file_to_attach):

    zipFile_path= f'./../data/results/{zip_file_to_attach}.zip'

    # Getting destinary credentials
    to = input('Receiver mail CC: ')
    while not re.match(r'[^@]+@[^@]+\.[^@]+', to):
        print('Invalid email. Try again...')
        to = input('Receiver mail CC: ')

    # Getting sender credentials
    if not 'emailPassword' in os.environ:
        raise ValueError ('You should pass a email password')

    gmail_user = os.environ['email']
    gmail_password = os.environ['emailPassword']

    # Writing content in the email
    subject = f'Pipelines Project Results'

    #Constructing email
    message = StringIO.StringIO()
    email_msg = MimeWriter.MimeWriter(message)
    email_msg.addheader('To', to)
    email_msg.addheader('From', sender)
    email_msg.addheader('Subject', subject)
    email_msg.addheader('MIME-Version', '1.0')

    email_msg.startmultipartbody('mixed')

    part = email_msg.nextpart()
    body = part.startbody('text/plain')
    part.flushheaders()
    body.write(text)

    filename = os.path.basename(zipFile_path)
    ftype, encoding = 'application/zip', None

    part = email_msg.nextpart()
    part.addheader('Content-Transfer-Encoding', encoding)
    body = part.startbody("%s; name=%s" % (ftype, filename))
    mimetools.encode(open(zipFile_path, 'rb'), body, encoding)

    email_msg.lastpart()

    email_text = message.getvalue()

    #sending email
    smtp = smtplib.SMTP(SERVER, PORT)
    smtp.login(USER, PASSWORD)
    smtp.sendmail(sender, to, email_text)
    smtp.quit()
Exemplo n.º 28
0
    def sendmail(self,
                 server='127.0.0.1',
                 port=25,
                 sender='',
                 to='',
                 subject='',
                 text='',
                 attachments=None):
        message = StringIO.StringIO()
        writer = MimeWriter.MimeWriter(message)

        toaddr = ", ".join(to)

        writer.addheader('To', toaddr)
        writer.addheader('From', sender)
        writer.addheader('Subject', subject)
        writer.addheader('MIME-Version', '1.0')

        writer.startmultipartbody('mixed')

        part = writer.nextpart()
        body = part.startbody('text/html')
        part.flushheaders()
        body.write(text)

        if attachments is not None:
            for a in attachments:
                filename = os.path.basename(a)
                ctype, encoding = mimetypes.guess_type(a)

                if ctype is None:
                    ctype = 'application/octet-stream'
                    encoding = 'base64'
                elif ctype == 'text/plain':
                    encoding = 'quoted-printable'
                else:
                    encoding = 'base64'

                part = writer.nextpart()
                part.addheader('Content-Transfer-Encoding', encoding)
                body = part.startbody("%s; name=%s" % (ctype, filename))
                mimetools.encode(open(a, 'rb'), body, encoding)

        writer.lastpart()

        smtp = smtplib.SMTP(server, port)
        smtp.set_debuglevel(1)
        smtp.sendmail(sender, to, message.getvalue())
        smtp.quit()

        return
Exemplo n.º 29
0
	def send_attachment(self, mail_from = '', to = '', subject = '', attach_list = None, html_file = ''):
                """
                        Send email  with attachment
                """
	
		message = StringIO.StringIO()
                writer = MimeWriter.MimeWriter(message)

                writer = MimeWriter.MimeWriter(message)

                writer.addheader('To', to)
                writer.addheader('From', mail_from)
                writer.addheader('Subject', subject)
                writer.addheader('MIME-Version', '1.0')

                writer.startmultipartbody('mixed')
                writer.flushheaders()

                # start with a text/plain part
                part = writer.nextpart()
                body = part.startbody('text/plain', [("charset", 'utf-8')])
                part.flushheaders()

                for text in open(html_file):
                        body.write(text.encode('utf-8'))

                	# now add the attachments
		if attach_list is not None:
               	 	for attachment in attach_list:
                		for attach in attachment.split(","):
                        		filename = os.path.basename(attach)

                                	ctype, encoding = mimetypes.guess_type(attach)
                                	if ctype is None:
                                		ctype = 'application/octet-stream'
                                        	encoding = 'base64'
                                	elif ctype == 'text/plain':
                                		encoding = 'quoted-printable'
                                	else:
                                        	encoding = 'base64'

                                	part = writer.nextpart()
                                	part.addheader('Content-Transfer-Encoding', encoding)

                               	 	body = part.startbody("%s; name=%s" % (ctype, filename))
                                	mimetools.encode(open(attach, 'rb'), body, encoding)

                writer.lastpart()
                msg = message.getvalue()

                return msg
Exemplo n.º 30
0
	def send_mail():
		print "[CrashlogAutoSubmit] - send_mail"
		if len(crashLogFilelist):
			for crashlog in crashLogFilelist:
				filename = str(os.path.basename(crashlog))
				subpart = writer.nextpart()
				subpart.addheader("Content-Transfer-Encoding", 'base64')
				subpart.addheader("Content-Disposition",'attachment; filename="%s"' % filename)
				subpart.addheader('Content-Description', 'Enigma2 crashlog')
				body = subpart.startbody("%s; name=%s" % ('application/octet-stream', filename))
				mimetools.encode(open(crashlog, 'rb'), body, 'base64')
		writer.lastpart()
		sending = smtp.sendmail(str(mxServer), mailFrom, mailTo, message.getvalue())
		sending.addCallback(handleSuccess).addErrback(handleError)
Exemplo n.º 31
0
def sendMail():
    # Import smtplib for the actual sending function
    import smtplib
    import MimeWriter
    import mimetools
    import StringIO
    encoding = "base64"
    charset = "utf8"

    sender = u'*****@*****.**'
    to = [u'pastix-log@localhost']
    #declaration des buffers
    out = StringIO.StringIO()
    html = _index(10).replace(
        "<STYLE>", "<STYLE>%s" % open(
            u'/home/pastix/pastix-user/ricar/Scripts/regression/www/pastix.css'
        ).read())
    htmlin = StringIO.StringIO(html)
    txtin = StringIO.StringIO("Ne fonctionne qu'en HTML")

    #declaration et initialisation du writer
    writer = MimeWriter.MimeWriter(out)
    writer.addheader("Subject", "Regression")
    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()

    #ajout de la partie text
    textPart = writer.nextpart()
    textPart.addheader("Content-Transfer-Encoding", encoding)
    pout = textPart.startbody("text/plain", [("charset", charset)])
    mimetools.encode(txtin, pout, encoding)
    txtin.close()

    #On ajoute la partie html
    htmlPart = writer.nextpart()
    htmlPart.addheader("Content-Transfer-Encoding", encoding)
    pout = htmlPart.startbody("text/html", [("charset", charset)])
    mimetools.encode(htmlin, pout, encoding)
    htmlin.close()

    #on clot le mail
    writer.lastpart()
    mail = out.getvalue()
    out.close()
    smtp = smtplib.SMTP()
    smtp.connect()

    smtp.sendmail(sender, to, mail)
    smtp.close()
Exemplo n.º 32
0
	def send_mail():
		print "[CrashlogAutoSubmit] - send_mail"
		if len(crashLogFilelist):
			for crashlog in crashLogFilelist:
				filename = str(os.path.basename(crashlog))
				subpart = writer.nextpart()
				subpart.addheader("Content-Transfer-Encoding", 'base64')
				subpart.addheader("Content-Disposition",'attachment; filename="%s"' % filename)
				subpart.addheader('Content-Description', 'Enigma2 crashlog')
				body = subpart.startbody("%s; name=%s" % ('application/octet-stream', filename))
				mimetools.encode(open(crashlog, 'rb'), body, 'base64')
		writer.lastpart()
		sending = smtp.sendmail(str(mxServer), mailFrom, mailTo, message.getvalue())
		sending.addCallback(handleSuccess).addErrback(handleError)
Exemplo n.º 33
0
def mail(sender='', to='', subject='', text='', attachments=None, verbose=False):
    """
    Usage:
        mail()
    Params:
        sender: sender's email address
        to: receipient email address
        subject: subject line
        text: Email message body main part.
        attachments: list of files to attach
    """
    message = StringIO.StringIO()
    writer = MimeWriter.MimeWriter(message)
    writer.addheader('To', to)
    writer.addheader('From', sender)
    writer.addheader('Subject', subject)
    writer.addheader('MIME-Version', '1.0')
    
    writer.startmultipartbody('mixed')
    
    # start with a text/plain part
    part = writer.nextpart()
    body = part.startbody('text/plain')
    part.flushheaders()
    body.write(text)

    # now add the attachments
    if attachments is not None:
        for a in attachments:
            filename = os.path.basename(a)
            ctype, encoding = mimetypes.guess_type(a)
            if ctype is None:
                ctype = 'application/octet-stream'
                encoding = 'base64'
            elif ctype == 'text/plain':
                encoding = 'quoted-printable'
            else:
                encoding = 'base64'
                
            part = writer.nextpart()
            part.addheader('Content-Transfer-Encoding', encoding)
            body = part.startbody("%s; name=%s" % (ctype, filename))
            print filename
            mimetools.encode(open(a, 'rb'), body, encoding)

    # that's all folks
    writer.lastpart()

    send(sender,to,message.getvalue(),verbose)
Exemplo n.º 34
0
def get_image(uri):
    """
    Get image from uri and return a tuple containing the mime type of
    the image and a base64 representation of the image.

    Arguments:
    - `uri`: Uri for the image to fetch
    """
    log = logging.getLogger(__name__)
    log.info("Getting image from %s", uri)
    fd = urllib.urlopen(uri)
    mime_msg = fd.info()
    output = StringIO.StringIO()
    mimetools.encode(fd, output, 'base64')
    return (mime_msg.get('Content-Type'), output.getvalue())
Exemplo n.º 35
0
def _encode(body, encode=None):
    if encode is None:
        return body
    mfile = StringIO(body)
    mo = mimetools.Message(mfile)
    if mo.getencoding() != '7bit':
        raise MailHostError, 'Message already encoded'
    newmfile = StringIO()
    newmfile.write(''.join(mo.headers))
    newmfile.write('Content-Transfer-Encoding: %s\n' % encode)
    if not mo.has_key('Mime-Version'):
        newmfile.write('Mime-Version: 1.0\n')
    newmfile.write('\n')
    mimetools.encode(mfile, newmfile, encode)
    return newmfile.getvalue()
Exemplo n.º 36
0
def _encode(body, encode=None):
    if encode is None:
        return body
    mfile=StringIO(body)
    mo=mimetools.Message(mfile)
    if mo.getencoding() != '7bit':
        raise MailHostError, 'Message already encoded'
    newmfile=StringIO()
    newmfile.write(''.join(mo.headers))
    newmfile.write('Content-Transfer-Encoding: %s\n' % encode)
    if not mo.has_key('Mime-Version'):
        newmfile.write('Mime-Version: 1.0\n')
    newmfile.write('\n')
    mimetools.encode(mfile, newmfile, encode)
    return newmfile.getvalue()
Exemplo n.º 37
0
def sendMail():
   # Import smtplib for the actual sending function
   import smtplib
   import MimeWriter  
   import mimetools
   import StringIO  
   encoding = "base64"
   charset = "utf8"
 
   sender  = u'*****@*****.**'
   to      = [u'pastix-log@localhost']
   #declaration des buffers
   out = StringIO.StringIO() 
   html = _index(10).replace("<STYLE>", 
                             "<STYLE>%s" % open(u'/home/pastix/pastix-user/ricar/Scripts/regression/www/pastix.css').read())
   htmlin = StringIO.StringIO(html)
   txtin = StringIO.StringIO("Ne fonctionne qu'en HTML")
   
   #declaration et initialisation du writer
   writer = MimeWriter.MimeWriter(out)
   writer.addheader("Subject", "Regression")
   writer.addheader("MIME-Version", "1.0")
   writer.startmultipartbody("alternative")
   writer.flushheaders()
 
   #ajout de la partie text
   textPart = writer.nextpart()
   textPart.addheader("Content-Transfer-Encoding", encoding)
   pout = textPart.startbody("text/plain", [("charset", charset)])
   mimetools.encode(txtin, pout, encoding)
   txtin.close()
 
   #On ajoute la partie html
   htmlPart = writer.nextpart()
   htmlPart.addheader("Content-Transfer-Encoding", encoding)
   pout = htmlPart.startbody("text/html", [("charset", charset)])
   mimetools.encode(htmlin, pout, encoding)
   htmlin.close()
   
   #on clot le mail
   writer.lastpart()
   mail = out.getvalue()
   out.close()
   smtp = smtplib.SMTP()
   smtp.connect()

   smtp.sendmail(sender, to, mail)
   smtp.close()
Exemplo n.º 38
0
def createhtmlmail(subject, html, text=None):
    """
    Create a mime-message that will render as HTML or text as appropriate.
    If no text is supplied we use htmllib to guess a text rendering. 
    (so html needs to be well formed) 
    
    Adapted from recipe 13.5 from Python Cookbook 2
    """
    import MimeWriter, mimetools, StringIO
    if text is None:
        # produce an approximate text from the HTML input
        import htmllib
        import formatter
        textout = StringIO.StringIO()
        formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
        parser = htmllib.HTMLParser(formtext)
        parser.feed(html)
        parser.close()
        text = textout.getvalue()
        del textout, formtext, parser
    out = StringIO.StringIO()  # output buffer for our message
    htmlin = StringIO.StringIO(html)  # input buffer for the HTML
    txtin = StringIO.StringIO(text)  # input buffer for the plain text
    writer = MimeWriter.MimeWriter(out)
    # Set up some basic headers. Place subject here because smtplib.sendmail
    # expects it to be in the message, as relevant RFCs prescribe.
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    # Start the multipart section of the message. Multipart/alternative seems
    # to work better on some MUAs than multipart/mixed.
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    # the plain-text section: just copied through, assuming iso-8859-1  # XXXX always true ?
    subpart = writer.nextpart()
    pout = subpart.startbody("text/plain", [("charset", 'iso-8859-l')])
    pout.write(txtin.read())
    txtin.close()
    # the HTML subpart of the message: quoted-printable, just in case
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    # You're done; close your writer and return the message as a string
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg
Exemplo n.º 39
0
def createhtmlmail(subject, html, text=None):
    """
    Create a mime-message that will render as HTML or text as appropriate.
    If no text is supplied we use htmllib to guess a text rendering. 
    (so html needs to be well formed) 
    
    Adapted from recipe 13.5 from Python Cookbook 2
    """
    import MimeWriter, mimetools, io
    if text is None:
        # produce an approximate text from the HTML input
        import htmllib
        import formatter
        textout = io.StringIO()
        formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
        parser = htmllib.HTMLParser(formtext)
        parser.feed(html)
        parser.close()
        text = textout.getvalue()
        del textout, formtext, parser
    out = io.StringIO()       # output buffer for our message
    htmlin = io.StringIO(html)  # input buffer for the HTML
    txtin = io.StringIO(text)   # input buffer for the plain text
    writer = MimeWriter.MimeWriter(out)
    # Set up some basic headers. Place subject here because smtplib.sendmail
    # expects it to be in the message, as relevant RFCs prescribe.
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    # Start the multipart section of the message. Multipart/alternative seems
    # to work better on some MUAs than multipart/mixed.
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    # the plain-text section: just copied through, assuming iso-8859-1  # XXXX always true ?
    subpart = writer.nextpart()
    pout = subpart.startbody("text/plain", [("charset", 'iso-8859-l')]) 
    pout.write(txtin.read())
    txtin.close()
    # the HTML subpart of the message: quoted-printable, just in case
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    # You're done; close your writer and return the message as a string
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg    
Exemplo n.º 40
0
def makePart(body, encoding):
	msg = Message(StringIO())
	msg["Content-Transfer-Encoding"] =  encoding
	out = StringIO()
	if encoding != "base64":
		encode(StringIO(replace(body,"\r","")), out, encoding)
	else:
		encode(StringIO(body), out, encoding)
	msg.body = out.getvalue()
	if encoding == "quoted-printable":
		lines = split(msg.body, "\n")
		for i in xrange(len(lines)):
			if lines[i] and lines[i][:5] == 'From ':
				lines[i] = "=%02x" % ord("F") + lines[i][1:]
		msg.body = join(lines, "\n")
	return msg
Exemplo n.º 41
0
def createhtmlmail(subject, html, text=None):
    # 创建MIME消息,最终呈现为HTML或文本
    import MimeWriter, mimetools, cStringIO

    if text is None:
        # 创建HTML字符串呈现的纯文本内容
        # 除非通过参数制定了更好的纯文本版本
        import htmllib, formatter

        textout = cStringIO.StringIO()
        formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
        parser = htmllib.HTMLParser(formtext)
        parser.feed(html)
        parser.close()
        text = textout.getvalue()
        del textout, formtext, parser
    out = cStringIO.StringIO()  # 消息的输出缓存
    htmlin = cStringIO.StringIO(html)  # HTML的输入缓存
    txtin = cStringIO.StringIO(text)  # 纯文本的输入缓存
    writer = MimeWriter.MimeWriter(out)
    # 设置一些基本的头部,在此放入标题,根据RFC的规定
    # smtplib.sendmail会在消息中找标题
    writer.addheader("subject", subject)
    writer.addheader("MIME-Version", "1.0")
    # 消息的多头部分,在某些邮件客户端中Multipart/alternatives
    # 比multipart/mixed 工作得更好
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    # 纯文本段:直接复制,假设为iso-8859-1
    subpart = writer.nextpart()
    pout = subpart.startbody("text/plain", [("charset", "iso-8859-1")])
    pout.write(txtin.read())
    txtin.close()
    # 消息的HTML部分:设为quoted-printable,以防万一
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", "us-ascii")])
    mimetools.encode(htmlin, pout, "quoted-printable")
    htmlin.close()
    # 完工;关闭writer并将消息作为字符串返回
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg
Exemplo n.º 42
0
def createhtmlmail(html, headers):
    """
    Create a mime-message that will render HTML in popular
    MUAs, text in better ones

    Based on: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67083
    """
    import MimeWriter
    import mimetools
    import cStringIO

    out = cStringIO.StringIO()  # output buffer for our message
    htmlin = cStringIO.StringIO(html)

    text = re.sub('<.*?>', '', html)
    txtin = cStringIO.StringIO(text)

    # FIXME MimeWriter is deprecated as of Python 2.6
    writer = MimeWriter.MimeWriter(out)
    for header, value in headers:
        writer.addheader(header, value)
    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()

    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
    mimetools.encode(txtin, pout, 'quoted-printable')
    txtin.close()

    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()

    writer.lastpart()
    msg = out.getvalue()
    out.close()

    return msg
Exemplo n.º 43
0
def createhtmlmail(html, headers):
    """
    Create a mime-message that will render HTML in popular
    MUAs, text in better ones

    Based on: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67083
    """
    import MimeWriter
    import mimetools
    import cStringIO
    
    out = cStringIO.StringIO() # output buffer for our message 
    htmlin = cStringIO.StringIO(html)

    text = re.sub('<.*?>', '', html)
    txtin = cStringIO.StringIO(text)

    # FIXME MimeWriter is deprecated as of Python 2.6
    writer = MimeWriter.MimeWriter(out)
    for header,value in headers:
        writer.addheader(header, value)
    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()

    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
    mimetools.encode(txtin, pout, 'quoted-printable')
    txtin.close()

    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()

    writer.lastpart()
    msg = out.getvalue()
    out.close()

    return msg
Exemplo n.º 44
0
def createhtmlmail(subject, html, text=None):
    # 创建MIME消息,最终呈现为HTML或文本
    import MimeWriter, mimetools, cStringIO
    if text is None:
        # 创建HTML字符串呈现的纯文本内容
        # 除非通过参数制定了更好的纯文本版本
        import htmllib, formatter
        textout = cStringIO.StringIO()
        formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
        parser = htmllib.HTMLParser(formtext)
        parser.feed(html)
        parser.close()
        text = textout.getvalue()
        del textout, formtext, parser
    out = cStringIO.StringIO()  # 消息的输出缓存
    htmlin = cStringIO.StringIO(html)  # HTML的输入缓存
    txtin = cStringIO.StringIO(text)  # 纯文本的输入缓存
    writer = MimeWriter.MimeWriter(out)
    # 设置一些基本的头部,在此放入标题,根据RFC的规定
    # smtplib.sendmail会在消息中找标题
    writer.addheader("subject", subject)
    writer.addheader("MIME-Version", "1.0")
    # 消息的多头部分,在某些邮件客户端中Multipart/alternatives
    # 比multipart/mixed 工作得更好
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    # 纯文本段:直接复制,假设为iso-8859-1
    subpart = writer.nextpart()
    pout = subpart.startbody("text/plain", [("charset", 'iso-8859-1')])
    pout.write(txtin.read())
    txtin.close()
    # 消息的HTML部分:设为quoted-printable,以防万一
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    # 完工;关闭writer并将消息作为字符串返回
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg
Exemplo n.º 45
0
 def __create_flash_email(self, p_html_content, p_text_content, p_to,
                          p_from, p_subject):
     #creates a mime-message that will render as text
     if isinstance(p_html_content, unicode):
         p_html_content = p_html_content.encode('utf-8')
     if isinstance(p_text_content, unicode):
         p_text_content = p_text_content.encode('utf-8')
     if isinstance(p_subject, unicode):
         p_subject = p_subject.encode('utf-8')
     htmlin = cStringIO.StringIO(p_html_content)
     textin = cStringIO.StringIO(p_text_content)
     out = cStringIO.StringIO()
     writer = MimeWriter.MimeWriter(out)
     # set up some basic headers... we put subject here
     writer.addheader("From", p_from)
     writer.addheader("To", p_to)
     writer.addheader("Subject", p_subject)
     writer.addheader(
         "Date", time.strftime("%a, %d %b %Y %H:%M:%S +0000",
                               time.gmtime()))
     writer.addheader("MIME-Version", "1.0")
     # start the multipart section of the message
     writer.startmultipartbody("alternative")
     writer.flushheaders()
     # the plain text section
     subpart = writer.nextpart()
     subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
     pout = subpart.startbody("text/plain", [("charset", 'utf-8')])
     mimetools.encode(textin, pout, 'quoted-printable')
     textin.close()
     # the html subpart of the message
     subpart = writer.nextpart()
     subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
     pout = subpart.startbody("text/html", [("charset", 'utf-8')])
     mimetools.encode(htmlin, pout, 'quoted-printable')
     htmlin.close()
     #close your writer and return the message body
     writer.lastpart()
     msg = out.getvalue()
     out.close()
     return msg
Exemplo n.º 46
0
def createhtmlmail(subject, message_file, recipient):
    f = open(message_file, 'r')
    nonunique = f.read()
    f.close()
    unique = nonunique.replace("$IDENTIFIER$", base64.b64encode(recipient))
    out = cStringIO.StringIO()
    htmlin = cStringIO.StringIO(unique)
    writer = MimeWriter.MimeWriter(out)
    writer.addheader("To", recipient)
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg
Exemplo n.º 47
0
def createhtmlmail(subject, message_file, recipient):
    f = open(message_file, 'r')
    nonunique = f.read()
    f.close()
    unique = nonunique.replace("$IDENTIFIER$", base64.b64encode(recipient))
    out = cStringIO.StringIO()
    htmlin = cStringIO.StringIO(unique)
    writer = MimeWriter.MimeWriter(out)
    writer.addheader("To", recipient)
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg
Exemplo n.º 48
0
def sendHtmlMail(email_from, email_to, subject, text, html):
    """
    Sends emails.
    
    """
    encoding = "quoted-printable"
    charset = "utf-8"

    out = StringIO.StringIO() 
    htmlin = StringIO.StringIO(html.encode('utf-8'))
    txtin = StringIO.StringIO(text.encode('utf-8'))
                          
    writer = MimeWriter.MimeWriter(out)
    writer.addheader("Subject", subject)
    writer.addheader("To", email_to)

    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()
                
    textPart = writer.nextpart()
    textPart.addheader("Content-Transfer-Encoding", encoding)
    pout = textPart.startbody("text/plain", [("charset", charset)])
    mimetools.encode(txtin, pout, encoding)
    txtin.close()
                                                                        
    htmlPart = writer.nextpart()
    htmlPart.addheader("Content-Transfer-Encoding", encoding)
    pout = htmlPart.startbody("text/html", [("charset", charset)])
    mimetools.encode(htmlin, pout, encoding)
    htmlin.close()
                        
    writer.lastpart()
    mail = out.getvalue()
    out.close()
    smtp = smtplib.SMTP("localhost")
    smtp.sendmail(email_from, [email_to], mail.encode('utf-8'))
    smtp.close()
Exemplo n.º 49
0
    def send_html_email(self, fake_mail, mail_to, subject, text, html_content):
        """
                        Send html email 
                """

        out = cStringIO.StringIO()
        htmlin = cStringIO.StringIO(html_content)
        txtin = cStringIO.StringIO(text)

        writer = MimeWriter.MimeWriter(out)

        writer.addheader("From", fake_mail)
        writer.addheader("Subject", subject)
        writer.addheader("MIME-Version", "1.0")
        writer.addheader("To", mail_to)

        writer.startmultipartbody("alternative")
        writer.flushheaders()

        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
        pout = subpart.startbody("text/plain", [("charset", 'utf-8')])
        mimetools.encode(txtin, pout, 'quoted-printable')
        txtin.close()

        subpart = writer.nextpart()
        subpart.addheader("Content-Transfer-Encoding", "quoted-printable")

        pout = subpart.startbody("text/html", [("charset", 'utf-8')])
        mimetools.encode(htmlin, pout, 'quoted-printable')
        htmlin.close()

        writer.lastpart()
        msg = out.getvalue()
        out.close()

        return msg
Exemplo n.º 50
0
def send_mail(sender=None,
              receiver=None,
              message=None,
              server=None,
              auth=None,
              debug=False,
              subject=None,
              encoding='quoted-printable',
              attachments=None):
    # FIXME: How to generate and send mails: a step by step tutorial
    # FIXME: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e0793c1007361398/
    # FIXME: google for aspineux blog

    if message is None:
        return False

    message = message.lstrip().lstrip('\r\n').lstrip()

    if sender is None:
        sender = default_mail_sender

    if receiver is None:
        receiver = [default_mail_receiver]

    if server is None:
        server = default_mail_server

    if subject is None:
        subject = u'gmTools.py: send_mail() test'

    msg = StringIO.StringIO()
    writer = MimeWriter.MimeWriter(msg)
    writer.addheader('To', u', '.join(receiver))
    writer.addheader('From', sender)
    writer.addheader('Subject', subject[:50].replace('\r',
                                                     '/').replace('\n', '/'))
    writer.addheader('MIME-Version', '1.0')

    writer.startmultipartbody('mixed')

    # start with a text/plain part
    part = writer.nextpart()
    body = part.startbody('text/plain')
    part.flushheaders()
    body.write(message.encode(encoding))

    # now add the attachments
    if attachments is not None:
        for attmt in attachments:
            filename = os.path.basename(attmt[0])
            try:
                mtype = attmt[1]
                encoding = attmt[2]
            except IndexError:
                mtype, encoding = mimetypes.guess_type(attmt[0])
                if mtype is None:
                    mtype = 'application/octet-stream'
                    encoding = 'base64'
                elif mtype == 'text/plain':
                    encoding = 'quoted-printable'
                else:
                    encoding = 'base64'

            part = writer.nextpart()
            part.addheader('Content-Transfer-Encoding', encoding)
            body = part.startbody("%s; name=%s" % (mtype, filename))
            mimetools.encode(open(attmt[0], 'rb'), body, encoding)

    writer.lastpart()

    import smtplib
    failed = False
    refused = []
    try:
        session = smtplib.SMTP(server)
        session.set_debuglevel(debug)
        session.starttls()
        session.ehlo()
        if auth is not None:
            session.login(auth['user'], auth['password'])
        refused = session.sendmail(sender, receiver, msg.getvalue())
        session.quit()
    except smtplib.SMTPException:
        failed = True
        _log.exception('cannot send mail')
        gmLog2.log_stack_trace()

    msg.close()
    if len(refused) > 0:
        _log.error("refused recipients: %s" % refused)

    if failed:
        return False

    return True
Exemplo n.º 51
0
def sendmail ( to_addrs, subj, msg, 
               from_addr = Configuration.FromAddress,
               **extended ):
    """**
    <p>The general-purpose sendmail function, which is called
    by the STML &lt;:sendmail:&gt; tag, or directly by Python code.</p>
    <p><tt>to_addrs</tt> should be a list or tuple of email address
    strings. <tt>subj</tt> must be a string, although it may be empty.
    <tt>msg</tt> is a string containing the body of the message; it can
    be empty. <tt>from_addr</tt> is a single mail address string; it 
    defaults to the value of the <tt>FromAddress</tt> variable in 
    <tt>templating.conf</tt>.</p>
    <p>This function returns nothing on success, and raises a
    <code>MailError</code> on any mail failure.</p>
    <p>
    The From: and To: headers are always built from supplied parameters.
    Cc: and Bcc: headers in the supplied mail text are not touched
    and not used.
    </p>
    <p>
    The sendmail function adds a correct Date: header, ensures that
    the From: header is set and generates a Message-Id: header if
    necessary. If the raw parameter is true, these headers are
    not touched.
    </p>

    <p>
    The extended parameter accepts the following parameters:
    </p>
    <dl>
     <dt>to_name='name'</dt>
     <dd>A name that may be used in the To: header
         directly. It's merged with to_addrs if the there is only one value for
         to_addrs. If there are multiple to_addrs, it is used
         literally and may then contain an address too.</dd>
     <dt>from_name</dt>
     <dd>A name that is merged with from_addr in the From: header.</dd>
     <dt>envelope_sender</dt>
     <dd>The sender address that is used in the SMTP dialogue. This
         address gets possible bounces.</dd>
     <dt>charset='charset-name'</dt>
     <dd>The character set that is used for encoding of headers
         and the message body. At the moment only <tt>iso-8859-1</tt>
         and <tt>us-ascii</tt> are supported because of limitations
         in the rfc822 module. The default is us-ascii</dd>
     <dt>encoding='encoding-type'</dt>
     <dd>The encoding type that is used for encoding of headers
         and the message body.<br />
         Possible values are <tt>base64</tt>, <tt>7bit</tt>,
         <tt>8bit</tt> and <tt>quoted-printable</tt><br />
         When 7bit is used, the MIME headers (Mime-Version,
         Content-Encoding and Content-Type are not set (and deleted
         if present in the msg).<br />
         The default value is 7bit.</dd>
     <dt>raw=True</dt>
     <dd>If this parameter is set to true the contents of the message
         is not altered in any way. The message is given in the parameter
         <tt>msg</tt>. In this case the envelope_sender
         has to be set, the receivers are taken from to_addrs as
         usual</dd>
    </dl>
    """

    # force SkunkWeb administrator to change the default envelope sender
    if from_addr == 'root@localhost':
        WARN("MailServices: FromAddress not changed, use a deliverable address!")
        raise MailError, "FromAddress not changed, use a deliverable address!"
    

    # if they supplied only a string as to_addrs (i.e. one address),
    # make it a list
    if type(to_addrs) == type(''):
        to_addrs = [to_addrs]
    rnum = len(to_addrs)       # number of receivers

    # do defined address checks, raise exception in case of problems
    address_check(_addresscheck_level, to_addrs)

    # check if the message is to be sent 'as is'
    if extended.has_key('raw') and extended['raw']:
        if not extended.has_key('envelope_sender'):
           WARN("MailServices: envelope_sender not set, but 'raw' send requested")
           raise MailError, "envelope_sender not set, but 'raw' send requested"
        dispatch_to_send_method(to_addrs, msg, extended['envelope_sender'])
        return

    # charset setting
    if extended.has_key('charset'):
        charset = string.lower(extended['charset'])
        if charset not in valid_charsets:
           WARN("MailServices: invalid character set parameter given: %s" \
	         % (extended['charset']))
           raise MailError, "invalid character set parameter given"
    else:
        charset = 'us-ascii'

    # check envelope sender
    if extended.has_key('envelope_sender'):
        envelope_sender = extended['envelope_sender']
    else:
        envelope_sender = from_addr

    mailfile = StringIO(msg)
    mail = mimetools.Message(mailfile)

    # insert subject
    if not subj or subj == '':
        subj = 'no subject'
    # work around limitation in mimify
    mail['Subject'] = mimify.mime_encode_header(subj + ' <')[:-2]

    # insert from header
    if extended.has_key('from_name'):
        fromheader = extended['from_name'] + ' <' + from_addr + '>'
        fromheader = mimify.mime_encode_header(fromheader)
    else:
        fromheader = from_addr
    mail['From'] = fromheader

    # insert to header
    if extended.has_key('to_name'):
        toheader = extended['to_name']
        if rnum == 1:
            if len(filter(lambda x: x in ['<','>'], list(toheader))) != 0:
                WARN("MailServices: angle bracket in to_name when using single recipient")
                raise MailError, "angle bracket in to_name when using single recipient"
            toheader = toheader + ' <' + to_addrs[0] + '>'
        mail['To'] = mimify.mime_encode_header(toheader)
    else:    
        if rnum == 1:
            mail['To'] = to_addrs[0]
        else:
            mail['To'] = "recipient list not shown: ;"

    # required Date: header
    lt=time.time()
    mail['Date']=arpa(lt)

    # not necessary but useful - Message-Id
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(lt))
    pid = os.getpid()
    idhost = socket.getfqdn()
    randint = random.randrange(100000)
    mail['Message-Id'] = \
             '<%s.%s.%s.skunkweb@%s>' % (utcdate, pid, randint, idhost)

    # character set
    if extended.has_key('charset'):
        charset = string.lower(extended['charset'])
        if charset not in ['us-ascii', 'iso-8859-1']:
            WARN("MailServices: charset %s is not supported" % (charset))
            raise MailError, "charset %s is not supported" % (charset)
    else:
        charset = 'us-ascii'

    # encoding
    if extended.has_key('encoding'):
        encoding = string.lower(extended['encoding'])
        if encoding not in ['7bit', '8bit', 'base64', 'quoted-printable']:
            WARN("MailServices: encoding %s is not supported" % (encoding))
            raise MailError, "encoding %s is not supported" % (encoding)
    else:
        encoding = '7bit'

    # check the presence of 8bit data
    if len(filter(lambda x: ord(x) > 127, list(msg))) > 0:
        eightbitdata = True
    else:
        eightbitdata = False

    if encoding == '7bit':
        # check for correctness
        if charset != 'us-ascii':
            WARN("MailServices: 7bit encoding but charset is not us-ascii")
            raise MailError, "7bit encoding but charset is not us-ascii"
        if eightbitdata:
            WARN("MailServices: 7bit encoding but 8bit data present")
            raise MailError, "7bit encoding but 8bit data present"
        # delete present MIME headers if 7bit encoding is used
        if mail.has_key('Content-Transfer-Encoding'):
            del mail['Content-Transfer-Encoding']
        if mail.has_key('Mime-Version'):
            del mail['Mime-Version']
        if mail.has_key('Content-Type'):
            del mail['Content-Type']
    else:                                     # not 7bit
        mail['Content-Transfer-Encoding'] = encoding
        mail['Mime-Version'] = '1.0'
        mail['Content-Type'] = 'text/plain; charset=%s' % (charset)
        headers = mail.__str__() + '\n'
        mail.rewindbody()
        body = mailfile.read()
        mailfile.close()
        mailfile=StringIO(body)
        newmfile = StringIO()
        # only encode body - mimetools doesn't check this
        mimetools.encode(mailfile, newmfile, encoding)
        mailfile = StringIO(headers + newmfile.getvalue())
        newmfile.close()
        mail = mimetools.Message(mailfile)

    mail.rewindbody()
    messagetext = mail.__str__() + '\n' + mailfile.read()
    mailfile.close()
    # now send
    dispatch_to_send_method(to_addrs, messagetext, envelope_sender)
Exemplo n.º 52
0
from test_support import TestFailed
import mimetools

import string, StringIO
start = string.ascii_letters + "=" + string.digits + "\n"
for enc in ['7bit', '8bit', 'base64', 'quoted-printable']:
    print enc,
    i = StringIO.StringIO(start)
    o = StringIO.StringIO()
    mimetools.encode(i, o, enc)
    i = StringIO.StringIO(o.getvalue())
    o = StringIO.StringIO()
    mimetools.decode(i, o, enc)
    if o.getvalue() == start:
        print "PASS"
    else:
        print "FAIL"
        print o.getvalue()
Exemplo n.º 53
0
from test_support import TestFailed
import mimetools
import string, StringIO
start = string.ascii_letters + "=" + string.digits + "\n"
for enc in ['7bit', '8bit', 'base64', 'quoted-printable']:
    print enc,
    i = StringIO.StringIO(start)
    o = StringIO.StringIO()
    mimetools.encode(i, o, enc)
    i = StringIO.StringIO(o.getvalue())
    o = StringIO.StringIO()
    mimetools.decode(i, o, enc)
    if o.getvalue() == start:
        print "PASS"
    else:
        print "FAIL"
        print o.getvalue()

Exemplo n.º 54
0
def sendHtmlMail(smtpServer,
                 sender,
                 receiver,
                 subject,
                 html,
                 user=None,
                 password=None):
    "Sends an html email (html argument is an HTML string)"
    import MimeWriter
    import mimetools
    import io

    # Produce an approximate textual rendering of the HTML string,
    # unless you have been given a better version as an argument
    import htmllib, formatter
    textout = io.StringIO()
    formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
    parser = htmllib.HTMLParser(formtext)
    parser.feed(html)
    parser.close()
    text = textout.getvalue()
    del textout, formtext, parser

    out = io.StringIO()  # output buffer for our message
    htmlin = io.StringIO(html)
    txtin = io.StringIO(text)

    writer = MimeWriter.MimeWriter(out)

    # Set up some basic headers. Place subject here
    # because smtplib.sendmail expects it to be in the
    # message body, as relevant RFCs prescribe.
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")

    # Start the multipart section of the message.
    # Multipart/alternative seems to work better
    # on some MUAs than multipart/mixed.
    writer.startmultipartbody("alternative")
    writer.flushheaders()

    # the plain-text section: just copied through, assuming iso-8859-1
    subpart = writer.nextpart()
    pout = subpart.startbody("text/plain", [("charset", 'iso-8859-1')])
    pout.write(txtin.read())
    txtin.close()

    # the HTML subpart of the message: quoted-printable, just in case
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()

    # You're done; close your writer and return the message body
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    smtpServer._sendMail(smtpServer,
                         sender,
                         receiver,
                         msg,
                         user=user,
                         password=password)
Exemplo n.º 55
0
    def render(self, md):
        contents=[]
        IO = StringIO()
        IO.write("Mime-Version: 1.0\n")
        mw = MimeWriter(IO)
        outer = mw.startmultipartbody(self.multipart)
        for x in self.sections:
            a, b = x
            has_key=a.has_key

            if has_key('skip_expr') and a['skip_expr'].eval(md):
                continue

            inner = mw.nextpart()

            if has_key('type_expr'): t=a['type_expr'].eval(md)
            else: t=a['type']

            if has_key('disposition_expr'): d=a['disposition_expr'].eval(md)
            else: d=a['disposition']

            if has_key('encode_expr'): e=a['encode_expr'].eval(md)
            else: e=a['encode']

            if has_key('name_expr'): n=a['name_expr'].eval(md)
            else: n=a['name']

            if has_key('filename_expr'): f=a['filename_expr'].eval(md)
            else: f=a['filename']

            if has_key('cid_expr'): cid=a['cid_expr'].eval(md)
            else: cid=a['cid']

            if has_key('charset_expr'): charset=a['charset_expr'].eval(md)
            else: charset=a['charset']

            if d:
                if f:
                    inner.addheader('Content-Disposition', '%s;\n filename="%s"' % (d, f))
                else:
                    inner.addheader('Content-Disposition', d)

            inner.addheader('Content-Transfer-Encoding', e)

            if cid:
                inner.addheader('Content-ID', '<%s>' % cid)

            if n:
                plist = [('name', n)]
            else:
                plist = []

            if t.startswith('text/'):
                plist.append(('charset', charset or 'us-ascii'))

            innerfile = inner.startbody(t, plist, 1)

            output = StringIO()
            if e == '7bit':
                innerfile.write(render_blocks(b, md))
            else:
                mimetools.encode(StringIO(render_blocks(b, md)),
                                 output, e)
                output.seek(0)
                innerfile.write(output.read())

        # XXX what if self.sections is empty ??? does it matter that mw.lastpart() is called
        # right after mw.startmultipartbody() ?
        if x is self.sections[-1]:
            mw.lastpart()

        outer.seek(0)
        return outer.read()