adding smtp provider devel
authorSandro Knauß <knauss@netzguerilla.net>
Tue, 14 Feb 2012 21:31:06 +0100
branchdevel
changeset 166 6d6890f7e3f8
parent 165 dd07766f4fee
child 167 374f34025fa1
adding smtp provider
iro/anbieter/smtp.py
iro/model/message.py
iro/offer/__init__.py
iro/offer/provider.py
iro/offer/smtp.py
--- a/iro/anbieter/smtp.py	Tue Feb 14 21:30:17 2012 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,107 +0,0 @@
-# -*- coding: utf-8 -*-
-#Copyright (C) 2009  Sandro Knauß <bugs@sandroknauss.de>
-
-#This program is free software; you can redistribute it and/or modify it under the terms
-#of the GNU General Public License as published by the Free Software Foundation;
-#either version 3 of the License, or any later version.
-#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
-#without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-#See the GNU General Public License for more details.
-
-#You should have received a copy of the GNU General Public License
-#along with this program; if not, see <http://www.gnu.org/licenses/>.
-
-class anbieter:
-    default_conf = ''    # override this
-import smtplib
-import ConfigParser
-import logging
-import copy
-
-logger=logging.getLogger("SMTP")
-
-class SMTP():
-    def __init__(self,config_filenames=None,section="smtp"):
-        self.config_filenames=config_filenames
-        self.section=section
-        self.bStart=False
-        self.bTLS=False
-        self.bSSL=False
-        self.max_recipients=1
-        
-
-    def read_basic_config(self,config_filenames=None):
-        """Read basic options from the config file"""
-        if not (config_filenames is None):
-            self.config_filenames=config_filenames
-        
-        cp = ConfigParser.ConfigParser()
-        cp.read(self.config_filenames)
-        self.config_parser = cp
-        self.send_from=cp.get(self.section, 'send_from')
-        self.host=cp.get(self.section, 'host')
-        self.port=cp.get(self.section, 'port')
-        self.user=cp.get(self.section, 'user')
-        self.pw=cp.get(self.section, 'password')
-        
-        try:
-            self.bTLS=cp.getboolean(self.section, 'TLS')
-        except ValueError:
-            self.bTLS=False
-        
-        try:
-            self.bSSL=cp.getboolean(self.section, 'SSL')
-        except ValueError:
-            self.bSSL=False
-
-    def prepareSMTP(self):
-        if self.bSSL:
-            self.smtp = smtplib.SMTP_SSL(self.host,self.port)
-        else:
-            self.smtp = smtplib.SMTP(self.host,self.port)
-        
-        if self.bTLS:
-            self.smtp.starttls()
-        
-        if not self.user == "":
-            self.smtp.login(self.user,self.pw)
-        
-        self.bStart=True
-
-    def sendMail(self,mail,recipients):   
-        logger.debug('SMTP.sendMail(%s,%s)'%(mail,  str(recipients)))
-        if not self.bStart:
-            self.prepareSMTP()
-       
-        frm=self.send_from
-        
-        if mail.getFrom():
-            frm = mail.getFrom()
-        
-        mail.content['From'] = frm 
-	
-
-        while len(recipients) > 0:
-            tmp_recipients=recipients[:self.max_recipients]
-	    tmpmail=copy.deepcopy(mail)
-            tmpmail.content['To']=", ".join(tmp_recipients)
-            logger.debug('self.smtp.sendmail(%s,%s,%s)'%(frm,  str(tmp_recipients), tmpmail.as_string()))
-            self.smtp.sendmail(frm,  tmp_recipients, tmpmail.as_string())
-            self.updateStatus( arranged=tmp_recipients)
-            recipients = recipients[self.max_recipients:]
-        
-        self.shutdownSMTP()
-
-
-    def updateStatus(self, arranged=None, failed=None):
-        """is a function that is called, if a new SMS/FAX was send
-        -arranged is non None, if SMS/FAX was sended successfully
-        -failed is non None, if SMS/FAX sending failed
-        the content will be the recipent"""
-        pass
-
-    def shutdownSMTP(self):
-        self.smtp.quit()
-        self.bStart=False
-    
-    
--- a/iro/model/message.py	Tue Feb 14 21:30:17 2012 +0100
+++ b/iro/model/message.py	Tue Feb 14 21:31:06 2012 +0100
@@ -61,7 +61,7 @@
         Message.__init__(self, con, typ='mail')
 
     def as_string(self):
-        return self.Message.as_string()
+        return self.content.as_string()
 
     def getFrom(self):
         return self.frm
--- a/iro/offer/__init__.py	Tue Feb 14 21:30:17 2012 +0100
+++ b/iro/offer/__init__.py	Tue Feb 14 21:31:06 2012 +0100
@@ -11,3 +11,4 @@
     except KeyError:
         raise NoProvider(typ)
 
+from .smtp import SMTP
--- a/iro/offer/provider.py	Tue Feb 14 21:30:17 2012 +0100
+++ b/iro/offer/provider.py	Tue Feb 14 21:31:06 2012 +0100
@@ -1,10 +1,13 @@
 from functools import partial
 
 class Provider():
-    def __init__(self, name, config, routes=[]):
+    def __init__(self, name, config, routes=[], typs=[]):
         self.name = name
         self.config = config
         self.routes=routes
+        self.typs=typs
+        self.testmode = False
+        
         self.loadConfig()
 
     def loadConfig(self):
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/iro/offer/smtp.py	Tue Feb 14 21:31:06 2012 +0100
@@ -0,0 +1,90 @@
+# -*- coding: utf-8 -*-
+#Copyright (C) 2009  Sandro Knauß <bugs@sandroknauss.de>
+
+#This program is free software; you can redistribute it and/or modify it under the terms
+#of the GNU General Public License as published by the Free Software Foundation;
+#either version 3 of the License, or any later version.
+#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+#without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+#See the GNU General Public License for more details.
+
+#You should have received a copy of the GNU General Public License
+#along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+import smtplib
+import copy
+
+from ..model.status import Status
+from ..error import UnknownOption, NeededOption, NoRoute, NoTyp
+from ..offer import providers
+from .provider import Provider
+
+class SMTP(Provider):
+    def __init__(self, name, config):
+        Provider.__init__(self,name,config,["std"],["mail"])
+        
+
+    def loadConfig(self):
+        """Read options from config"""
+        needed=["send_from","host", "port", "user", "password"]
+
+        for n in needed:
+            setattr(self,n,None)
+
+        Provider.loadConfig(self)
+        self.bTLS = False
+        self.bSSL = False
+
+        for (n, v) in self.config:
+            if n in needed:
+                setattr(self,n,v)
+            elif n == "TLS":
+                self.bTLS = bool(v)
+            elif n == "SSL":
+                self.bSSL = bool(v)
+            else:
+                raise UnknownOption(self.name, n)
+
+        for n in needed:
+           if getattr(self,n) is None:
+               raise NeededOption(self.name, n) 
+
+    def send(self,mail,recipient):   
+        try:
+            if not self.testmode:
+                if self.bSSL:
+                    smtp = smtplib.SMTP_SSL(self.host,self.port)
+                else:
+                    smtp = smtplib.SMTP(self.host,self.port)
+                
+                if self.bTLS:
+                    smtp.starttls()
+               
+                if not self.user == "":
+                    smtp.login(self.user,self.pw)
+            try:
+                frm=self.send_from
+                
+                if mail.getFrom():
+                    frm = mail.getFrom()
+                
+                tmpmail=copy.deepcopy(mail)
+                tmpmail.content['From'] = frm 
+                tmpmail.content['To']=recipient
+                if not self.testmode:
+                    smtp.sendmail(frm,  recipient, tmpmail.as_string())
+                return Status(self, "std")
+            finally:
+                smtp.quit()
+        except Exception as e:
+            return Status(self,"std",e)
+
+    def getSendFunc(self, typ, route):
+        if typ != "mail":
+            raise NoTyp(route)
+        elif  route != "std":
+            raise NoRoute(route)
+        return self.send
+
+providers["smtp"]=SMTP
+