connect to SMTP on-demand

This commit is contained in:
Martin Zimmermann 2013-09-13 19:51:56 +02:00
parent 98ab6d205a
commit 30fa254023
3 changed files with 27 additions and 9 deletions

View File

@ -150,7 +150,7 @@ def main():
"[SMTP]",
"username = ", "password = ",
"host = localhost", "port = 465", "ssl = on",
"recipient = ", "sender = "
"to = ", "from = "
]
args = parser.parse_args()

View File

@ -96,7 +96,7 @@ class Threads(object):
rv = con.execute("SELECT title FROM threads WHERE path=?", (path,)).fetchone()
if rv is not None:
return rv[0]
raise KeyError
return None
def add(self, path, title):
with sqlite3.connect(self.dbpath) as con:

View File

@ -23,19 +23,36 @@ def create(comment, subject, permalink, remote_addr):
return subject, u'\n'.join(rv)
class Connection(object):
def __init__(self, conf):
self.conf = conf
def __enter__(self):
self.server = (SMTP_SSL if self.conf.getboolean('SMTP', 'ssl') else SMTP)(
host=self.conf.get('SMTP', 'host'), port=self.conf.getint('SMTP', 'port'))
if self.conf.get('SMTP', 'username') and self.conf.get('SMTP', 'password'):
self.server.login(self.conf.get('SMTP', 'username'),
self.conf.get('SMTP', 'password'))
return self.server
def __exit__(self, exc_type, exc_value, traceback):
self.server.quit()
class SMTPMailer(object):
def __init__(self, conf):
self.server = (SMTP_SSL if conf.getboolean('SMTP', 'ssl') else SMTP)(
host=conf.get('SMTP', 'host'), port=conf.getint('SMTP', 'port'))
if conf.get('SMTP', 'username') and conf.get('SMTP', 'password'):
self.server.login(conf.get('SMTP', 'username'), conf.get('SMTP', 'password'))
self.conf = conf
self.from_addr = conf.get('SMTP', 'from')
self.to_addr = conf.get('SMTP', 'to')
with Connection(self.conf):
pass
def sendmail(self, subject, body, retries=5):
msg = MIMEText(body, 'plain', 'utf-8')
@ -45,7 +62,8 @@ class SMTPMailer(object):
for i in range(retries):
try:
self.server.sendmail(self.from_addr, self.to_addr, msg.as_string())
with Connection(self.conf) as con:
con.sendmail(self.from_addr, self.to_addr, msg.as_string())
except SMTPException:
logging.exception("uncaught exception, %i of %i:", i + 1, retries)
else: