iro/offer/smtp.py
author Sandro Knauß <knauss@netzguerilla.net>
Sat, 18 Feb 2012 19:48:54 +0100
branchdevel
changeset 171 5619596a0053
parent 169 aabc04843d25
child 180 55ab949cf0f8
permissions -rw-r--r--
getSendFunc logic from smtp to Provider(offer.provider)

# -*- 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
from ..offer import providers
from .provider import Provider

class SMTP(Provider):
    def __init__(self, name, config):
        Provider.__init__(self,name,config,{"mail":[None]})
        

    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):   
        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.password)
        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, None)
        finally:
            smtp.quit()

    def getSendFunc(self, typ, route):
        Provider.getSendFunc(self, typ, route)
        return self.send

providers["smtp"]=SMTP