|
| 1 | +import smtplib |
| 2 | + |
| 3 | +from textwrap import dedent |
| 4 | +from email.mime.text import MIMEText |
| 5 | + |
| 6 | +from base import BaseBackend |
| 7 | + |
| 8 | +class MailBackend(BaseBackend): |
| 9 | + subject = 'Pyres Failure on {queue}' |
| 10 | + |
| 11 | + recipients = [] |
| 12 | + from_user = None |
| 13 | + smtp_host = None |
| 14 | + smtp_port = 25 |
| 15 | + |
| 16 | + smtp_tls = False |
| 17 | + |
| 18 | + smtp_user = None |
| 19 | + smtp_password = None |
| 20 | + |
| 21 | + def save(self, resq=None): |
| 22 | + if not self.recipients or not self.smtp_host or not self.from_user: |
| 23 | + return |
| 24 | + |
| 25 | + message = self.create_message() |
| 26 | + subject = self.format_subject() |
| 27 | + |
| 28 | + message['Subject'] = subject |
| 29 | + message['From'] = self.from_user |
| 30 | + message['To'] = ", ".join(self.recipients) |
| 31 | + |
| 32 | + self.send_message(message) |
| 33 | + |
| 34 | + def format_subject(self): |
| 35 | + return self.subject.format(queue=self._queue, |
| 36 | + worker=self._worker, |
| 37 | + exception=self._exception) |
| 38 | + |
| 39 | + def create_message(self): |
| 40 | + """Returns a message body to send in this email.""" |
| 41 | + |
| 42 | + body = dedent("""\ |
| 43 | + Received exception {exception} on {queue} from worker {worker}: |
| 44 | +
|
| 45 | + {traceback} |
| 46 | +
|
| 47 | + Payload: |
| 48 | + {payload} |
| 49 | +
|
| 50 | + """).format(exception=self._exception, |
| 51 | + traceback=self._traceback, |
| 52 | + queue=self._queue, |
| 53 | + payload=self._payload, |
| 54 | + worker=self._worker) |
| 55 | + |
| 56 | + return MIMEText(body) |
| 57 | + |
| 58 | + def send_message(self, message): |
| 59 | + smtp = smtplib.SMTP(self.smtp_host, self.smtp_port) |
| 60 | + |
| 61 | + try: |
| 62 | + smtp.ehlo() |
| 63 | + |
| 64 | + if self.smtp_tls: |
| 65 | + smtp.starttls() |
| 66 | + |
| 67 | + if self.smtp_user: |
| 68 | + smtp.login(self.smtp_user, self.smtp_password) |
| 69 | + |
| 70 | + smtp.sendmail(self.from_user, self.recipients, message.as_string()) |
| 71 | + finally: |
| 72 | + smtp.close() |
0 commit comments