Improve notifier connection
This commit is contained in:
parent
e9e3958d2b
commit
705432c4a5
|
@ -1,4 +1,5 @@
|
|||
# -*- encoding: utf-8 -*-
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from email import encoders
|
||||
from email.mime.base import MIMEBase
|
||||
|
@ -27,14 +28,7 @@ class Notifier(object):
|
|||
smtp_pass: T.Text,
|
||||
smtp_from: T.Optional[T.Text] = None,
|
||||
) -> None:
|
||||
context = ssl.create_default_context()
|
||||
if smtp_starttls:
|
||||
self._conn = smtplib.SMTP_SSL(smtp_addr, smtp_port)
|
||||
self._greet = self._conn.ehlo
|
||||
else:
|
||||
self._conn = smtplib.SMTP(smtp_addr, smtp_port)
|
||||
self._greet = lambda: self._conn.starttls(context=context)
|
||||
|
||||
self._starttls = smtp_starttls
|
||||
self._addr = smtp_addr
|
||||
self._port = smtp_port
|
||||
self._user = smtp_user
|
||||
|
@ -42,14 +36,25 @@ class Notifier(object):
|
|||
self._from = smtp_from if smtp_from else smtp_user
|
||||
logger.info("%s initialized", self)
|
||||
|
||||
@contextmanager
|
||||
def connect(self):
|
||||
context = ssl.create_default_context()
|
||||
if self._starttls:
|
||||
with smtplib.SMTP(self._addr, self._port) as conn:
|
||||
conn.starttls(context=context)
|
||||
conn.login(self._user, self._pass)
|
||||
yield conn
|
||||
else:
|
||||
with smtplib.SMTP_SSL(self._addr, self._port) as conn:
|
||||
conn.login(self._user, self._pass)
|
||||
yield conn
|
||||
|
||||
def __str__(self) -> T.Text:
|
||||
return f"Notifier<{self._addr}:{self._port},from={self._from}>"
|
||||
|
||||
def send(self, to: T.List[T.Text], email: T.Text) -> None:
|
||||
self._greet()
|
||||
self._conn.login(self._user, self._pass)
|
||||
self._conn.sendmail(self._from, to, email)
|
||||
self._conn.close()
|
||||
with self.connect() as conn:
|
||||
conn.sendmail(self._from, to, email)
|
||||
|
||||
@retry_and_log(logger, RETRIES)
|
||||
def send_result(self, to: T.List[T.Text], result: bytes) -> None:
|
||||
|
|
Loading…
Reference in New Issue
Block a user