[controller] refactor send mail controller to use cwconfig.sendmails stable
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Fri, 09 Apr 2010 15:04:56 +0200
branchstable
changeset 5198 cf8292f80384
parent 5197 98dc05495e3e
child 5199 ebb50479d2ab
[controller] refactor send mail controller to use cwconfig.sendmails
cwconfig.py
web/views/basecontrollers.py
--- a/cwconfig.py	Fri Apr 09 12:23:39 2010 +0200
+++ b/cwconfig.py	Fri Apr 09 15:04:56 2010 +0200
@@ -1019,7 +1019,9 @@
         return i18n.compile_i18n_catalogs(sourcedirs, i18ndir, langs)
 
     def sendmails(self, msgs):
-        """msgs: list of 2-uple (message object, recipients)"""
+        """msgs: list of 2-uple (message object, recipients). Return False
+        if connection to the smtp server failed, else True.
+        """
         server, port = self['smtp-host'], self['smtp-port']
         SMTP_LOCK.acquire()
         try:
@@ -1028,7 +1030,7 @@
             except Exception, ex:
                 self.exception("can't connect to smtp server %s:%s (%s)",
                                server, port, ex)
-                return
+                return False
             heloaddr = '%s <%s>' % (self['sender-name'], self['sender-addr'])
             for msg, recipients in msgs:
                 try:
@@ -1039,6 +1041,7 @@
             smtp.close()
         finally:
             SMTP_LOCK.release()
+        return True
 
 set_log_methods(CubicWebConfiguration, logging.getLogger('cubicweb.configuration'))
 
--- a/web/views/basecontrollers.py	Fri Apr 09 12:23:39 2010 +0200
+++ b/web/views/basecontrollers.py	Fri Apr 09 15:04:56 2010 +0200
@@ -595,25 +595,14 @@
         for entity in rset.entities():
             yield entity
 
-    @property
-    @cached
-    def smtp(self):
-        mailhost, port = self._cw.config['smtp-host'], self._cw.config['smtp-port']
-        try:
-            return SMTP(mailhost, port)
-        except Exception, ex:
-            self.exception("can't connect to smtp server %s:%s (%s)",
-                             mailhost, port, ex)
-            url = self._cw.build_url(__message=self._cw._('could not connect to the SMTP server'))
-            raise Redirect(url)
-
     def sendmail(self, recipient, subject, body):
-        helo_addr = '%s <%s>' % (self._cw.config['sender-name'],
-                                 self._cw.config['sender-addr'])
         msg = format_mail({'email' : self._cw.user.get_email(),
                            'name' : self._cw.user.dc_title(),},
                           [recipient], body, subject)
-        self.smtp.sendmail(helo_addr, [recipient], msg.as_string())
+        if not self._cw.vreg.config.sendmails([(msg, [recipient])]):
+            msg = self._cw._('could not connect to the SMTP server')
+            url = self._cw.build_url(__message=msg)
+            raise Redirect(url)
 
     def publish(self, rset=None):
         # XXX this allows users with access to an cubicweb instance to use it as