avocado_job_mail.py 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
import logging
import smtplib
from email.mime.text import MIMEText

from avocado.core.settings import settings
from avocado.plugins.base import JobPre, JobPost


class Mail(JobPre, JobPost):

    name = 'mail'
    description = 'Sends mail to notify on job start/end'

    def __init__(self):
        self.log = logging.getLogger("avocado.app")
        self.rcpt = settings.get_value(section="plugins.job.mail",
                                       key="recipient",
                                       key_type=str,
                                       default='root@localhost.localdomain')
        self.subject = settings.get_value(section="plugins.job.mail",
                                          key="subject",
                                          key_type=str,
                                          default='[AVOCADO JOB NOTIFICATION]')
        self.sender = settings.get_value(section="plugins.job.mail",
                                         key="sender",
                                         key_type=str,
                                         default='avocado@localhost.localdomain')
        self.server = settings.get_value(section="plugins.job.mail",
                                         key="server",
                                         key_type=str,
                                         default='localhost')

    def mail(self, job):
        # build proper subject based on job status
        subject = '%s Job %s - Status: %s' % (self.subject,
                                              job.unique_id,
                                              job.status)
        msg = MIMEText(subject)
        msg['Subject'] = self.subject
        msg['From'] = self.sender
        msg['To'] = self.rcpt

        # So many possible failures, let's just tell the user about it
        try:
            smtp = smtplib.SMTP(self.server)
            smtp.sendmail(self.sender, [self.rcpt], msg.as_string())
            smtp.quit()
        except:
            self.log.error("Failure to send email notification: "
                           "please check your mail configuration")

    pre = post = mail