Commits

illume  committed 4ac28ac

Added SendMessage apps which can be used for contact forms and such things.

  • Participants
  • Parent commits 2cee705

Comments (0)

Files changed (4)

File newsletter/newsletterapp/newsletterapp.ini

 [/admin]
 tools.basic_auth.on = True
 tools.basic_auth.realm = 'Please Enter User/Password'
-tools.basic_auth.users = {"admin": newsletter.newsletterapp.newsletterapp.encrypt_pwd("admin")}
+
+# set up your users password like this.  Secure by default means there are no default users.
+#tools.basic_auth.users = {"admin": newsletter.newsletterapp.newsletterapp.encrypt_pwd("youradminpassword")}
+tools.basic_auth.users = {}
 tools.basic_auth.encrypt = newsletter.newsletterapp.newsletterapp.encrypt_pwd
 
 [newsletter]
 smtp_sleep_between_sends = 1.0
 
 
+
 # ----------------------
-#  experimental.  well, more experimental than the other bits.
+#  send_message_ parts...
 
 
-
-[send_message]
+[send_message_a_contact]
 # ----------------------
-# TODO: perhaps these should be a list of special send_message parts.
-#   since we should want to add multiple ones of these.
-#  Adding separate ones should just be like adding multiple apps into the tree.
+#  You can add multiple SendMessage instances. 
+# To make more, create new sections starting with send_message_
+# These are useful for things like contact forms.
 
 # exposed if you want to be able to send emails using a send_message url.
+send_message = True
+
+# where you want this one mounted.
+mount_point = "contact"
+
+# set this to True if you want this to work.  Secure by default means it does not work.
 exposed = False
+
+# the email template to use for the body of the message.
 email_template = "send_message_email_template"
+
+# the email template to use for the subject
 email_subject_template = "send_message_email_subject_template"
+
+# the html returned.
 template = "send_message_template"
+
+
 fromaddr = "yourname@example.com"
 
 # if this is empty then we get this from the toaddr input.
 toaddr = "sendingto@example.com"
 
-# optional lol auth key.  see source
-lolauth_key = ""
+# validate_input is a function which can be used to validate the input.
+#    set to None to do no validation
+validate_input = None
+#validate_input = lambda kwargs: kwargs.get('input', '') == 'ok input'
+#validate_input = mypackage.myvalidator
 
 
 

File newsletter/newsletterapp/newsletterapp.py

 
 
 
+def create_SendMessages(mount_on, config):
+    """ from the config given search for send_message_ ones.
+        create instances of SendMessage on the object mount_on
+    """
+    for k in config.keys():
+        if k.startswith("send_message_"):
+            send_message_config = config[k]
+            if send_message_config['send_message']:
+                setattr(mount_on, 
+                        send_message_config["mount_point"], 
+                        SendMessage(config["newsletter"], 
+                                    send_message_config, 
+                                    mount_on))
+
+
+
+class SendMessage(object):
+    
+    def __init__(self, config, send_message_config, web_newsletter):
+        self.config = config
+        self.send_message_config = send_message_config
+        self.web_newsletter = web_newsletter
+
+    def __call__(self, **kwargs):
+        return self.send_message(**kwargs)
+    
+    def send_message(self, **kwargs):
+        """ send_message(**kwargs) sends message 
+
+            NOTE: Not exposed by default.  Need to enable it in config
+
+            kwargs are used as variables to replace in the body and subject.
+
+            wrap_it - if True we wrap html response in a header footer.
+            toaddr - a single email address to send to.
+        """
+        if not self.send_message_config['exposed']:
+            raise ValueError("not exposed")
+
+        if not self.validate_input(kwargs):
+            raise ValueError("not what we were expecting")
+        
+        wrap_it = kwargs.get('wrap_it', None)
+
+
+        email_template = self.send_message_config.get('email_template')
+        email_subject_template = self.send_message_config.get('email_subject_template')
+        template = self.send_message_config.get('template')
+        
+        toaddr = self.send_message_config.get('toaddr', '')
+
+        # We get the toaddr from the kwargs if it is set to None in the header
+        if toaddr is None:
+            toaddr = kwargs.get('toaddr')
+            if not validate_email(toaddr):
+                raise ValueError("toaddr invalid")
+        
+        if toaddr == '':
+            raise ValueError("toaddr invalid")
+
+        replace_vars = dict(kwargs)
+        replace_vars['toaddr'] = toaddr
+
+        subject = self.web_newsletter.admin.email_template(email_subject_template)
+        body = self.web_newsletter.admin.email_template(email_template)
+        
+
+        # replace the variables in the template.
+        subject = template_replace(subject, replace_vars)
+        body = template_replace(body, replace_vars)
+        
+        sendmail(self.send_message_config.get('fromaddr'), 
+                toaddr, subject, body, 
+                self.config.get('smtp_host'), 
+                self.config.get('smtp_username'), 
+                self.config.get('smtp_password'),
+                self.config.get('sendmail_cmd'),
+                )
+        
+        return self.web_newsletter.html_template(template, wrap_it)
+        
+        
+    def validate_input(self, kwargs):
+        """ returns True if the input is valid.
+        """
+        # see if a validation function has been used defined in the config file.
+        validate_input = self.send_message_config.get('validate_input', None)
+        if validate_input is not None:
+            return validate_input(kwargs)
+        
+        return True
+
+
+
+
+
 
 
 
         """ load(config) loads the application given the configuration.
         """
         self.config = config["newsletter"]
-        self.send_message_config = config["send_message"]
 
         self.static_dir = self.config.get("static_dir")
         self.db_dir = self.config.get("db_dir")
         self.fromaddr = self.config.get("from_addr")
 
         self._default_vars = {"base_url" : self.config.get('base_url'),
-                            }
-
-        if self.send_message_config.get('exposed', False):
-            self.send_message.exposed = True
+                             }
 
 
         self._n = MyNewsletter(self.config)
 
         self.admin = WebNewsletterAdmin(self._n, self._ns, self.config)
 
+        # mount any send_message_ from the config.
+        create_SendMessages(self, config)
+
+
+
     def html_template(self, template_name, 
                             wrap_it = None, 
                             replace_vars = None):
         tmpl = os.path.join(self.static_dir, "web_front_templates", 
                             template_name + ".html")
         the_html = open(tmpl, "rb").read()
+
+        # get rid of trailing new lines
+        if the_html[-1] == "\n":
+            the_html = the_html[:-1]
+
+
         if replace_vars is None:
             replace_vars = {}
 
             return self.html_template("confirm_unsubscribe", wrap_it)
 
 
-    def send_message(self, **kwargs):
-        """ send_message(**kwargs) sends message 
-
-            NOTE: Not exposed by default.  Need to enable it in config
-
-            kwargs are used as variables to replace in the body and subject.
-
-            wrap_it - if True we wrap html response in a header footer.
-            toaddr - 
-        """
-        
-        if not self.lol_auth():
-            raise ValueError("not what we were expecting")
-        
-        wrap_it = kwargs.get('wrap_it', None)
-
-
-        email_template = self.send_message_config.get('email_template')
-        email_subject_template = self.send_message_config.get('email_subject_template')
-        template = self.send_message_config.get('template')
-        
-        toaddr = self.send_message_config.get('toaddr', '')
-
-        if toaddr == '':
-            toaddr = kwargs.get('toaddr')
-            if not validate_email(toaddr):
-                raise ValueError("email invalid")
-        
-        subject = self.admin.email_template(email_subject_template)
-        body = self.admin.email_template(email_template)
-        
-        
-        # replace the variables in the template.
-        subject = template_replace(subject, kwargs)
-        body = template_replace(body, kwargs)
-        
-        sendmail(self.send_message_config.get('fromaddr'), 
-                toaddr, subject, body, 
-                self.config.get('smtp_host'), 
-                self.config.get('smtp_username'), 
-                self.config.get('smtp_password'),
-                self.config.get('sendmail_cmd'),
-                )
-        
-        return self.html_template(template, wrap_it)
-        
-        
-    def lolauth(self):
-        """ returns True if we pass authentication.
-        """
-        
-        # check that header is set to something we expected.
-        return True
-
 
 
 
         tmpl = os.path.join(self.static_dir, 
                             "email_templates", 
                             template_name + ".html")
-        return open(tmpl, "rb").read()
+        the_html = open(tmpl, "rb").read()
+
+        # get rid of trailing new lines
+        if the_html[-1] == "\n":
+            the_html = the_html[:-1]
+
+        return the_html
 
     def edit(self, newsletter_send_id = None):
         """ edit(newsletter_send_id) edits the given newsletter send.

File newsletter/newsletterapp/static/web_front_templates/send_message_template.html

 message sent out ok
-

File newsletter/newsletterapp/test_newsletterapp.py

     ...                          'static_dir': 'static'}}
 
 
+We add a config item for a SendMessage.  Which can be used for things like contact forms.
+
+    >>> cfg['send_message_a'] = dict(send_message = True, 
+    ...     mount_point = "contact", 
+    ...     exposed = True, 
+    ...     email_template = "send_message_email_template", 
+    ...     email_subject_template = "send_message_email_subject_template", 
+    ...     template = "send_message_template", 
+    ...     fromaddr = "yourname@example.com", 
+    ...     toaddr = "sendingto@example.com", 
+    ...     validate_input = lambda kwargs: kwargs.get('input', 'ok input') == 'ok input')
+
+
+Now we load it from the config.
+
     >>> wnl = newsletterapp.WebNewsletter()
     >>> wnl.load(cfg)
 
 Subscribe a user.
 
     >>> wnl.subscribe("joe@example.com", "Joe Bloggs", wrap_it = False)
-    'thank you for subscribing.  We sent you an email to confirm.\\n'
+    'thank you for subscribing.  We sent you an email to confirm.'
 
 See if confirmation email is send.
     >>> _sendmail_log
     36
 
     >>> wnl.confirm_subscribe('joe@example.com', confirm_id, wrap_it = False)
-    'thank you for confirming your subscription\\n'
+    'thank you for confirming your subscription'
 
 
 Admin section.
 
 
 
-Try a send_message
+Try out contact SendMessage instance.
 
+    >>> wnl.contact(bla="ok")
+    'message sent out ok'
 
+    >>> _sendmail_log[-1]
+    (('yourname@example.com', 'sendingto@example.com', 'a subject for sendingto@example.com ok', 'an example email ok for send_message', 'localhost', '', '', None), {})
 
+Check that the validate_input function defined in the cfg works.
+    >>> wnl.contact(input="not good input")
+    Traceback (most recent call last):
+    ...
+    ValueError: not what we were expecting
 
+Now with the expected input for input, so the validation passes.
+    >>> wnl.contact(input="ok input")
+    'message sent out ok'
 
 
 """