You can do what you want with it.

Ideally, somebody would fix the small bugs and incorporate it in TG.
Somebody with more python experience could probably make it more
efficient.

WHAT IT DOES
This class will send email.  There are 3 send methods.

testmail(to_addr, from_addr=None):
- sends a sample email.

sendemail(to_addr, html, from_addr=None, text=None, subject=None, ):
- Send html email to to_addr
- the text portion will default to a conversion of the HTML
- the subject line will default to the title of the HTML

sendkidemail( to_addr, kid_template, dict_args, from_addr=None,
subject=None ):
- Take a path to a kid template, pass the dict_args to it, generate
html, send it

ISSUES
The kid_template path is not like projectname.templates.kidname
I was not able to get that to work.

You have to use something like
projectname/templates/email.kid

You can not use the same TG templates.  The py:extends="'master.kid'"
causes problems that I was unable to resolve.  Remove it and use plain
templates.

Due to my lack of python experience, I was not sure how to pass
multiple args through so I opted for requiring a dict named args.  This
means a change in the way that variables are referenced.

TG syntax
<span py:replace="now">now</span>

Email Syntax
<span py:replace="args['now']">now</span>


SETTING IT UP
If you are using localhost, there is actually no setup.  otherwise, add
the following 4 lines to your cfg file.  The last 3 are optional.

email.smtp_server ="YOUR SMTP SERVER"
email.smtp_user = "YOUR SMTP USER ID"
email.smtp_password ="YOUR SMTP PASSWORD"
email.smtp_fromaddr ="YOUR Default From Address"

Anyway, this works well enough for my current needs.  Have fun with it.

Alvin


Start of Source Code - turboemail.py
-------------------------------------------------------------------------------------------------------------------
import turbogears
import cherrypy
import smtplib

# Chunks of code taken from Python Cookbook - Art Gillespie then
updated to 2.4 with SMTP authentication
#
# email.smtp_server ="YOUR SMTP SERVER"
# email.smtp_user = "YOUR SMTP USER ID"
# email.smtp_password ="YOUR SMTP PASSWORD"
# email.smtp_fromaddr ="YOUR Default From Address"

class TurboEmail:

        def testmail(self, to_addr, from_addr=None):
                html = "<html><body><h1>It works</h1></body></html>"
                text = "Text Message - It Works"
                subject = "TurboEmail Test"

                if from_addr ==None:
                        from_addr = cherrypy.config.get('email.from_addr')
                self.sendemail( to_addr, html, text, subject, from_addr)
                return

        def sendkidemail(self, to_addr, kid_template, dict_args,
from_addr=None, subject=None ):
                import kid
                import time
                # set defaults

#               't4modules/templates/email.kid'
                template_module = kid.load_template(file=kid_template)
                template = template_module.Template( args=dict_args)
                html =  str(template)
                self.sendemail( to_addr, html, from_addr)
                return

        def sendemail(self, to_addr, html, from_addr=None, text=None,
subject=None, ):
                # set defaults
                smtp_server = cherrypy.config.get('email.smtp_server', 
'localhost')
                smtp_user = cherrypy.config.get('email.smtp_user')
                smtp_password = cherrypy.config.get('email.smtp_password')

                if from_addr ==None:
                        from_addr = cherrypy.config.get('email.from_addr')

                if text == None:
                        text = self.html2text(html)

                if subject == None:
                        subject = self.get_title(html)

                msg = self.createhtmlmail(from_addr, to_addr, html, text, 
subject)
                s = smtplib.SMTP(smtp_server)
# Remove to get more debug messages
#               s.set_debuglevel(1)

# None - not tested, my smtp server has a password
                if smtp_user != None:
                        s.login(smtp_user, smtp_password)
                s.sendmail( from_addr, to_addr, msg)
                s.close()
                return


# returns a message to send
        def createhtmlmail(self, from_addr, to_addr, html, text, subject):
                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)
                #
                # 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("To", to_addr)
                writer.addheader("From", from_addr)
                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", 
'ISO-8859-1')])
                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()
                return msg

        def html2text(self, html):
                import formatter
                import htmllib
                from cStringIO import StringIO

                outstream = StringIO()
                w = formatter.DumbWriter(outstream)
                f = formatter.AbstractFormatter(w)
                p = htmllib.HTMLParser(f)
                p.feed(html)
                p.close()
                text = outstream.getvalue()
                outstream.close()
                return text

# use regular expressions to extract the title for subject line
        def get_title(self, html):
                import re

                p = re.compile('<title[^>]*>(.*?)</title>')
                m = p.search(html)
                if m:
                    p = re.compile( '<[^>]*>')
                    title = p.sub('', m.group(0))
                    return title
                # set your own default
                return "Email from Turbogears"

Reply via email to