iro/offer/smtp.py
author Sandro Knauß <knauss@netzguerilla.net>
Mon, 05 Mar 2012 23:52:29 +0100
branchdevel
changeset 218 91f87ad13540
parent 186 b381eaa774ab
child 220 602720314930
permissions -rw-r--r--
integration tests for smtp

# -*- 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 functools import partial

from ..validate import vInteger, vEmail,vBool
from ..model.status import Status
from ..config import Option
from .provider import Provider, providers

class SMTP(Provider):
    def __init__(self, name):
        Provider.__init__(self,name,{"mail":[None]})
        self.options.update({
            "send_from":Option(vEmail,long="Emailaddress from which mail will be sended.",must=True),
            "host":Option(lambda x,y:x, long="Hostname of MTA", must=True),
            "port":Option(partial(vInteger,minv=0),long="Port of the MTA", default=25),
            "user":Option(lambda x,y:x, long="username to login into MTA.",default=""),
            "password":Option(lambda x,y:x, long="password to login into MTA.",default=""),
            "TLS":Option(vBool,long="use TLS for connection to MTA", default=False),
            "SSL":Option(vBool,long="use SSL for connection to MTA", default=False),
            })

    def send(self, recipient, mail):   
        if not self.testmode:
            if self.SSL:
                smtp = smtplib.SMTP_SSL(self.host,self.port)
            else:
                smtp = smtplib.SMTP(self.host,self.port)
            
            if self.TLS:
                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