Example #1
0
 def assemble_email(self, exc_data):
     short_html_version, short_extra = self.format_html(exc_data, show_hidden_frames=False, show_extra_data=True)
     long_html_version, long_extra = self.format_html(exc_data, show_hidden_frames=True, show_extra_data=True)
     text_version = self.format_text(exc_data, show_hidden_frames=True, show_extra_data=True)[0]
     msg = MIMEMultipart()
     msg.set_type("multipart/alternative")
     msg.preamble = msg.epilogue = ""
     text_msg = MIMEText(as_str(text_version))
     text_msg.set_type("text/plain")
     text_msg.set_param("charset", "UTF-8")
     msg.attach(text_msg)
     html_msg = MIMEText(as_str(short_html_version) + as_str("".join(short_extra)))
     html_msg.set_type("text/html")
     html_msg.set_param("charset", "UTF-8")
     html_long = MIMEText(as_str(long_html_version) + as_str("".join(long_extra)))
     html_long.set_type("text/html")
     html_long.set_param("charset", "UTF-8")
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = as_str("%s: %s" % (exc_data.exception_type, formatter.truncate(str(exc_data.exception_value))))
     msg["Subject"] = as_str(self.subject_prefix) + subject
     msg["From"] = as_str(self.from_address)
     msg["To"] = as_str(", ".join(self.to_addresses))
     msg["Date"] = formatdate()
     return msg
Example #2
0
 def assemble_email(self, exc_data):
     short_html_version, short_extra = self.format_html(
         exc_data, show_hidden_frames=False, show_extra_data=True)
     long_html_version, long_extra = self.format_html(
         exc_data, show_hidden_frames=True, show_extra_data=True)
     text_version = self.format_text(exc_data,
                                     show_hidden_frames=True,
                                     show_extra_data=True)[0]
     msg = MIMEMultipart()
     msg.set_type('multipart/alternative')
     msg.preamble = msg.epilogue = ''
     text_msg = MIMEText(as_str(text_version))
     text_msg.set_type('text/plain')
     text_msg.set_param('charset', 'UTF-8')
     msg.attach(text_msg)
     html_msg = MIMEText(
         as_str(short_html_version) + as_str(''.join(short_extra)))
     html_msg.set_type('text/html')
     html_msg.set_param('charset', 'UTF-8')
     html_long = MIMEText(
         as_str(long_html_version) + as_str(''.join(long_extra)))
     html_long.set_type('text/html')
     html_long.set_param('charset', 'UTF-8')
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = as_str('%s: %s' %
                      (exc_data.exception_type,
                       formatter.truncate(str(exc_data.exception_value))))
     msg['Subject'] = as_str(self.subject_prefix) + subject
     msg['From'] = as_str(self.from_address)
     msg['To'] = as_str(', '.join(self.to_addresses))
     msg['Date'] = formatdate()
     return msg
 def assemble_email(self, exc_data):
     short_html_version = self.format_html(exc_data, show_hidden_frames=False)[0]
     long_html_version = self.format_html(exc_data, show_hidden_frames=True)[0]
     text_version = self.format_text(exc_data, show_hidden_frames=False)[0]
     msg = MIMEMultipart()
     msg.set_type("multipart/alternative")
     msg.preamble = msg.epilogue = ""
     text_msg = MIMEText(text_version)
     text_msg.set_type("text/plain")
     text_msg.set_param("charset", "ASCII")
     msg.attach(text_msg)
     html_msg = MIMEText(short_html_version)
     html_msg.set_type("text/html")
     # @@: Correct character set?
     html_msg.set_param("charset", "UTF-8")
     html_long = MIMEText(long_html_version)
     html_long.set_type("text/html")
     html_long.set_param("charset", "UTF-8")
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = "%s: %s" % (exc_data.exception_type, formatter.truncate(str(exc_data.exception_value)))
     msg["Subject"] = self.subject_prefix + subject
     msg["From"] = self.from_address
     msg["To"] = ", ".join(self.to_addresses)
     return msg
Example #4
0
 def assemble_email(self, exc_data):
     short_html_version = self.format_html(
         exc_data, show_hidden_frames=False)
     long_html_version = self.format_html(
         exc_data, show_hidden_frames=True)
     text_version = self.format_text(
         exc_data, show_hidden_frames=False)
     msg = MIMEMultipart()
     msg.set_type('multipart/alternative')
     msg.preamble = msg.epilogue = ''
     text_msg = MIMEText(text_version)
     text_msg.set_type('text/plain')
     text_msg.set_param('charset', 'ASCII')
     msg.attach(text_msg)
     html_msg = MIMEText(short_html_version)
     html_msg.set_type('text/html')
     # @@: Correct character set?
     html_msg.set_param('charset', 'UTF-8')
     html_long = MIMEText(long_html_version)
     html_long.set_type('text/html')
     html_long.set_param('charset', 'UTF-8')
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = '%s: %s' % (exc_data.exception_type,
                        formatter.truncate(str(exc_data.exception_value)))
     msg['Subject'] = self.subject_prefix + subject
     msg['From'] = self.from_address
     msg['To'] = ', '.join(self.to_addresses)
     return msg
Example #5
0
 def assemble_email(self, exc_data):
     short_html_version = self.format_html(
         exc_data, show_hidden_frames=False)
     long_html_version = self.format_html(
         exc_data, show_hidden_frames=True)
     text_version = self.format_text(
         exc_data, show_hidden_frames=False)
     msg = MIMEMultipart()
     msg.set_type('multipart/alternative')
     msg.preamble = msg.epilogue = ''
     text_msg = MIMEText(text_version)
     text_msg.set_type('text/plain')
     text_msg.set_param('charset', 'ASCII')
     msg.attach(text_msg)
     html_msg = MIMEText(short_html_version)
     html_msg.set_type('text/html')
     # @@: Correct character set?
     html_msg.set_param('charset', 'UTF-8')
     html_long = MIMEText(long_html_version)
     html_long.set_type('text/html')
     html_long.set_param('charset', 'UTF-8')
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = '%s: %s' % (exc_data.exception_type,
                           formatter.truncate(str(exc_data.exception_value)))
     msg['Subject'] = self.subject_prefix + subject
     msg['From'] = self.from_address
     msg['To'] = ', '.join(self.to_addresses)
     return msg
 def assemble_email(self, exc_data):
     short_html_version, short_extra = self.format_html(
         exc_data, show_hidden_frames=False, show_extra_data=True)
     long_html_version, long_extra = self.format_html(
         exc_data, show_hidden_frames=True, show_extra_data=True)
     text_version = self.format_text(
         exc_data, show_hidden_frames=True, show_extra_data=True)[0]
     msg = MIMEMultipart()
     msg.set_type('multipart/alternative')
     msg.preamble = msg.epilogue = ''
     text_msg = MIMEText(as_str(text_version))
     text_msg.set_type('text/plain')
     text_msg.set_param('charset', 'UTF-8')
     msg.attach(text_msg)
     html_msg = MIMEText(as_str(short_html_version) + as_str(''.join(short_extra)))
     html_msg.set_type('text/html')
     html_msg.set_param('charset', 'UTF-8')
     html_long = MIMEText(as_str(long_html_version) + as_str(''.join(long_extra)))
     html_long.set_type('text/html')
     html_long.set_param('charset', 'UTF-8')
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = as_str('%s: %s' % (exc_data.exception_type,
                                  formatter.truncate(str(exc_data.exception_value))))
     msg['Subject'] = as_str(self.subject_prefix) + subject
     msg['From'] = as_str(self.from_address)
     msg['To'] = as_str(', '.join(self.to_addresses))
     msg['Date'] = formatdate()
     return msg
Example #7
0
File: mail.py Project: hef/buildbot
    def createEmail(self, msgdict, builderName, title, results, build,
                    patch=None, logs=None):
        text = msgdict['body'].encode(ENCODING)
        type = msgdict['type']
        if 'subject' in msgdict:
            subject = msgdict['subject'].encode(ENCODING)
        else:
            subject = self.subject % { 'result': Results[results],
                                       'projectName': title,
                                       'title': title,
                                       'builder': builderName,
                                       }


        assert type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type

        if patch or logs:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type, ENCODING))
        else:
            m = Message()
            m.set_payload(text, ENCODING)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = subject
        m['From'] = self.fromaddr
        # m['To'] is added later

        if patch:
            a = MIMEText(patch[1].encode(ENCODING), _charset=ENCODING)
            a.add_header('Content-Disposition', "attachment",
                         filename="source patch")
            m.attach(a)
        if logs:
            for log in logs:
                name = "%s.%s" % (log.getStep().getName(),
                                  log.getName())
                if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name):
                    a = MIMEText(log.getText().encode(ENCODING), 
                                 _charset=ENCODING)
                    a.add_header('Content-Disposition', "attachment",
                                 filename=name)
                    m.attach(a)

        # Add any extra headers that were requested, doing WithProperties
        # interpolation if necessary
        if self.extraHeaders:
            properties = build.getProperties()
            for k,v in self.extraHeaders.items():
                k = properties.render(k)
                if k in m:
                    twlog.msg("Warning: Got header " + k + " in self.extraHeaders "
                          "but it already exists in the Message - "
                          "not adding it.")
                    continue
                m[k] = properties.render(v)

        return m
Example #8
0
     def createEmail(self, msgdict, builderName, projectName, results, 
                    patch=None, logs=None):
        text = msgdict['body'].encode(ENCODING)
        type = msgdict['type']
        if 'subject' in msgdict:
            subject = msgdict['subject'].encode(ENCODING)
        else:
            subject = self.subject % { 'result': Results[results],
                                       'projectName': projectName,
                                       'builder': builderName,
                                       }


        assert type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type

        if patch or logs:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type, ENCODING))
        else:
            m = Message()
            m.set_payload(text, ENCODING)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = subject
        m['From'] = self.fromaddr
        # m['To'] is added later

        if patch:
            a = MIMEText(patch[1].encode(ENCODING), _charset=ENCODING)
            a.add_header('Content-Disposition', "attachment",
                         filename="source patch")
            m.attach(a)
        if logs:
            for log in logs:
                name = "%s.%s" % (log.getStep().getName(),
                                  log.getName())
                if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name):
                    a = MIMEText(log.getText().encode(ENCODING),_subtype="html",
                                 _charset=ENCODING)
                    a.add_header('Content-Disposition', "attachment",
                                 filename=name)
                    m.attach(a)

        # Add any extra headers that were requested, doing WithProperties
        # interpolation if necessary
        if self.extraHeaders:
            for k,v in self.extraHeaders.items():
                k = properties.render(k)
                if k in m:
                    twlog("Warning: Got header " + k + " in self.extraHeaders "
                          "but it already exists in the Message - "
                          "not adding it.")
                    continue
                m[k] = properties.render(v)

        return m
Example #9
0
    def sendmail(self, subject, sender, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True):
        if recipients:
            if type(recipients) == type(""):
                recipients = [recipients]
            elif type(recipients) != type([]):
                raise Exception("Unexpected type for recipients.")
            if cc:
                if type(cc) == type(""):
                    recipients.append(cc)
                elif type(cc) == type([]):
                    recipients.extend(cc)
                else:
                    raise Exception("Unexpected type for cc.")
            recipients = join(recipients, ";")

            if plaintext and htmltext and useMIMEMultipart:
                msg = MIMEMultipart('alternative')
            else:
                msg = email.Message.Message()

            msg['Subject'] = subject
            msg['From'] = sender
            msg['To'] = recipients
            msg['Reply-To'] = sender
            if plaintext and htmltext and useMIMEMultipart:
                part1 = MIMEText(plaintext, 'plain')
                part2 = MIMEText(htmltext, 'html')
                msg.attach(part1)
                msg.attach(part2)
            else:
                msg.set_type("text/plain")
                msg.set_payload(plaintext)

            if debug:
                print(msg)
            else:
                if self.host and self.port:
                    s = smtplib.SMTP(self.host, self.port)
                elif self.host:
                    s = smtplib.SMTP(self.host)
                else:
                    s = smtplib.SMTP()
                s.connect()
                s.sendmail(msg['From'], recipients, msg.as_string())
                s.close()
            return True
        return False
Example #10
0
    def buildMessage(self, name, build, results):
        #
        # logs is a list of tuples that contain the log
        # name, log url, and the log contents as a list of strings.
        #
        logs = list()
        for logf in build.getLogs():
            logStep = logf.getStep()
            stepName = logStep.getName()
            logStatus, dummy = logStep.getResults()
            logName = logf.getName()
            logs.append(('%s.%s' % (stepName, logName),
                         '%s/steps/%s/logs/%s' % (self.status.getURLForThing(build), stepName, logName),
                         logf.getText().splitlines(),
                         logStatus))

        properties = build.getProperties()
                
        attrs = {'builderName': name,
                 'projectName': self.status.getProjectName(),
                 'mode': self.mode,
                 'result': Results[results],
                 'buildURL': self.status.getURLForThing(build),
                 'buildbotURL': self.status.getBuildbotURL(),
                 'buildText': build.getText(),
                 'buildProperties': properties,
                 'slavename': build.getSlavename(),
                 'reason':  build.getReason(),
                 'responsibleUsers': build.getResponsibleUsers(),
                 'branch': "",
                 'revision': "",
                 'patch': "",
                 'changes': [],
                 'logs': logs}

        ss = build.getSourceStamp()
        if ss:
            attrs['branch'] = ss.branch
            attrs['revision'] = ss.revision
            attrs['patch'] = ss.patch
            attrs['changes'] = ss.changes[:]

        text, type = self.customMesg(attrs)
        assert type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type

        haveAttachments = False
        if attrs['patch'] or self.addLogs:
            haveAttachments = True
            if not canDoAttachments:
                twlog.msg("warning: I want to send mail with attachments, "
                          "but this python is too old to have "
                          "email.MIMEMultipart . Please upgrade to python-2.3 "
                          "or newer to enable addLogs=True")

        if haveAttachments and canDoAttachments:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type))
        else:
            m = Message()
            m.set_payload(text)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = self.subject % { 'result': attrs['result'],
                                        'projectName': attrs['projectName'],
                                        'builder': attrs['builderName'],
                                        }
        m['From'] = self.fromaddr
        # m['To'] is added later

        if attrs['patch']:
            a = MIMEText(attrs['patch'][1])
            a.add_header('Content-Disposition', "attachment",
                         filename="source patch")
            m.attach(a)
        if self.addLogs:
            for log in build.getLogs():
                name = "%s.%s" % (log.getStep().getName(),
                                  log.getName())
                if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name):
                    a = MIMEText(log.getText())
                    a.add_header('Content-Disposition', "attachment",
                                 filename=name)
                    m.attach(a)

        # Add any extra headers that were requested, doing WithProperties
        # interpolation if necessary
        if self.extraHeaders:
            for k,v in self.extraHeaders:
                k = properties.render(k)
                if k in m:
                    twlog("Warning: Got header " + k + " in self.extraHeaders "
                          "but it already exists in the Message - "
                          "not adding it.")
                    continue
                m[k] = properties.render(v)

        # now, who is this message going to?
        dl = []
        recipients = []
        if self.sendToInterestedUsers and self.lookup:
            for u in build.getInterestedUsers():
                d = defer.maybeDeferred(self.lookup.getAddress, u)
                d.addCallback(recipients.append)
                dl.append(d)
        d = defer.DeferredList(dl)
        d.addCallback(self._gotRecipients, recipients, m)
        return d
Example #11
0
    def createEmail(self,
                    msgdict,
                    builderName,
                    title,
                    results,
                    builds=None,
                    patches=None,
                    logs=None):
        text = msgdict['body'].encode(ENCODING)
        type = msgdict['type']
        if 'subject' in msgdict:
            subject = msgdict['subject'].encode(ENCODING)
        else:
            subject = self.subject % {
                'result': Results[results],
                'projectName': title,
                'title': title,
                'builder': builderName,
            }

        assert '\n' not in subject, \
            "Subject cannot contain newlines"

        assert type in ('plain', 'html'), \
            "'%s' message type must be 'plain' or 'html'." % type

        if patches or logs:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type, ENCODING))
        else:
            m = Message()
            m.set_payload(text, ENCODING)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = subject
        m['From'] = self.fromaddr
        # m['To'] is added later

        if patches:
            for (i, patch) in enumerate(patches):
                a = self.patch_to_attachment(patch, i)
                m.attach(a)
        if logs:
            for log in logs:
                name = "%s.%s" % (log.getStep().getName(), log.getName())
                if (self._shouldAttachLog(log.getName())
                        or self._shouldAttachLog(name)):
                    text = log.getText()
                    if not isinstance(text, unicode):
                        text = text.decode(LOG_ENCODING)
                    a = MIMEText(text.encode(ENCODING), _charset=ENCODING)
                    a.add_header('Content-Disposition',
                                 "attachment",
                                 filename=name)
                    m.attach(a)

        #@todo: is there a better way to do this?
        # Add any extra headers that were requested, doing WithProperties
        # interpolation if only one build was given
        if self.extraHeaders:
            for k, v in self.extraHeaders.items():
                if len(builds) == 1:
                    k = interfaces.IProperties(builds[0]).render(k)
                if k in m:
                    twlog.msg("Warning: Got header " + k +
                              " in self.extraHeaders "
                              "but it already exists in the Message - "
                              "not adding it.")
                if len(builds) == 1:
                    m[k] = interfaces.IProperties(builds[0]).render(v)
                else:
                    m[k] = v

        return m
Example #12
0
    def createEmail(self, msgdict, builderName, title, results, builds=None,
                    patches=None, logs=None):
        text = msgdict['body'].encode(ENCODING)
        type = msgdict['type']
        if 'subject' in msgdict:
            subject = msgdict['subject'].encode(ENCODING)
        else:
            subject = self.subject % { 'result': Results[results],
                                       'projectName': title,
                                       'title': title,
                                       'builder': builderName,
                                       }

        assert '\n' not in subject, \
            "Subject cannot contain newlines"

        assert type in ('plain', 'html'), \
            "'%s' message type must be 'plain' or 'html'." % type

        if patches or logs:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type, ENCODING))
        else:
            m = Message()
            m.set_payload(text, ENCODING)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = subject
        m['From'] = self.fromaddr
        # m['To'] is added later

        if patches:
            for (i, patch) in enumerate(patches):
                a = self.patch_to_attachment(patch, i)
                m.attach(a)
        if logs:
            for log in logs:
                name = "%s.%s" % (log.getStep().getName(),
                                  log.getName())
                if ( self._shouldAttachLog(log.getName()) or
                     self._shouldAttachLog(name) ):
                    text = log.getText()
                    if not isinstance(text, unicode):
                        text = text.decode(LOG_ENCODING)
                    a = MIMEText(text.encode(ENCODING),
                                 _charset=ENCODING)
                    a.add_header('Content-Disposition', "attachment",
                                 filename=name)
                    m.attach(a)

        #@todo: is there a better way to do this?
        # Add any extra headers that were requested, doing WithProperties
        # interpolation if only one build was given
        if self.extraHeaders:
            if len(builds) == 1:
                extraHeaders = builds[0].render(self.extraHeaders)
            else:
                extraHeaders = self.extraHeaders
            for k,v in extraHeaders.items():
                if k in m:
                    twlog.msg("Warning: Got header " + k +
                      " in self.extraHeaders "
                      "but it already exists in the Message - "
                      "not adding it.")
                m[k] = v
    
        return m
Example #13
0
File: mail.py Project: zanxi/bitpop
    def createEmail(self, msgdict, builderName, title, results, builds=None, patches=None, logs=None):
        text = msgdict["body"].encode(ENCODING)
        type = msgdict["type"]
        if "subject" in msgdict:
            subject = msgdict["subject"].encode(ENCODING)
        else:
            subject = self.subject % {
                "result": Results[results],
                "projectName": title,
                "title": title,
                "builder": builderName,
            }

        assert type in ("plain", "html"), "'%s' message type must be 'plain' or 'html'." % type

        if patches or logs:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type, ENCODING))
        else:
            m = Message()
            m.set_payload(text, ENCODING)
            m.set_type("text/%s" % type)

        m["Date"] = formatdate(localtime=True)
        m["Subject"] = subject
        m["From"] = self.fromaddr
        # m['To'] is added later

        if patches:
            for (i, patch) in enumerate(patches):
                a = MIMEText(patch[1].encode(ENCODING), _charset=ENCODING)
                a.add_header("Content-Disposition", "attachment", filename="source patch " + str(i))
                m.attach(a)
        if logs:
            for log in logs:
                name = "%s.%s" % (log.getStep().getName(), log.getName())
                if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name):
                    a = MIMEText(log.getText().encode(ENCODING), _charset=ENCODING)
                    a.add_header("Content-Disposition", "attachment", filename=name)
                    m.attach(a)

        # @todo: is there a better way to do this?
        # Add any extra headers that were requested, doing WithProperties
        # interpolation if only one build was given
        if self.extraHeaders:
            for k, v in self.extraHeaders.items():
                if len(builds == 1):
                    k = builds[0].render(k)
                if k in m:
                    twlog.msg(
                        "Warning: Got header " + k + " in self.extraHeaders "
                        "but it already exists in the Message - "
                        "not adding it."
                    )
                continue
                if len(builds == 1):
                    m[k] = builds[0].render(v)
                else:
                    m[k] = v

        return m
Example #14
0
    def buildMessage(self, name, build, results):
        if self.customMesg:
            # the customMesg stuff can be *huge*, so we prefer not to load it
            attrs = self.getCustomMesgData(self.mode, name, build, results, self.master_status)
            text, type = self.customMesg(attrs)
            msgdict = {"body": text, "type": type}
        elif self.messageFormatter:
            msgdict = self.messageFormatter(self.mode, name, build, results, self.master_status)
        else:
            msgdict = self.defaultMessage(self.mode, name, build, results, self.master_status)

        text = msgdict["body"]
        type = msgdict["type"]
        if "subject" in msgdict:
            subject = msgdict["subject"]
        else:
            subject = self.subject % {
                "result": Results[results],
                "projectName": self.master_status.getProjectName(),
                "builder": name,
            }

        assert type in ("plain", "html"), "'%s' message type must be 'plain' or 'html'." % type

        haveAttachments = False
        ss = build.getSourceStamp()
        if (ss and ss.patch and self.addPatch) or self.addLogs:
            haveAttachments = True
            if not canDoAttachments:
                twlog.msg(
                    "warning: I want to send mail with attachments, "
                    "but this python is too old to have "
                    "email.MIMEMultipart . Please upgrade to python-2.3 "
                    "or newer to enable addLogs=True"
                )

        if haveAttachments and canDoAttachments:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type))
        else:
            m = Message()
            m.set_payload(text)
            m.set_type("text/%s" % type)

        m["Date"] = formatdate(localtime=True)
        m["Subject"] = subject
        m["From"] = self.fromaddr
        # m['To'] is added later

        if ss and ss.patch and self.addPatch:
            patch = ss.patch
            a = MIMEText(patch[1])
            a.add_header("Content-Disposition", "attachment", filename="source patch")
            m.attach(a)
        if self.addLogs:
            for log in build.getLogs():
                name = "%s.%s" % (log.getStep().getName(), log.getName())
                if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name):
                    a = MIMEText(log.getText())
                    a.add_header("Content-Disposition", "attachment", filename=name)
                    m.attach(a)

        # Add any extra headers that were requested, doing WithProperties
        # interpolation if necessary
        if self.extraHeaders:
            for k, v in self.extraHeaders.items():
                k = properties.render(k)
                if k in m:
                    twlog(
                        "Warning: Got header " + k + " in self.extraHeaders "
                        "but it already exists in the Message - "
                        "not adding it."
                    )
                    continue
                m[k] = properties.render(v)

        # now, who is this message going to?
        dl = []
        recipients = []
        if self.sendToInterestedUsers and self.lookup:
            for u in build.getInterestedUsers():
                d = defer.maybeDeferred(self.lookup.getAddress, u)
                d.addCallback(recipients.append)
                dl.append(d)
        d = defer.DeferredList(dl)
        d.addCallback(self._gotRecipients, recipients, m)
        return d
Example #15
0
    def buildMessage(self, name, build, results):
        if self.customMesg:
            # the customMesg stuff can be *huge*, so we prefer not to load it
            attrs = self.getCustomMesgData(self.mode, name, build, results, self.master_status)
            text, type = self.customMesg(attrs)
            msgdict = { 'body' : text, 'type' : type }
        else:
            msgdict = self.messageFormatter(self.mode, name, build, results, self.master_status)

        text = msgdict['body']
        type = msgdict['type']
        if 'subject' in msgdict:
            subject = msgdict['subject']
        else:
            subject = self.subject % { 'result': Results[results],
                                       'projectName': self.master_status.getProjectName(),
                                       'builder': name,
                                       }


        assert type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type

        ss = build.getSourceStamp()
        if (ss and ss.patch and self.addPatch) or self.addLogs:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type))
        else:
            m = Message()
            m.set_payload(text)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = subject
        m['From'] = self.fromaddr
        # m['To'] is added later

        if ss and ss.patch and self.addPatch:
            patch = ss.patch
            a = MIMEText(patch[1])
            a.add_header('Content-Disposition', "attachment",
                         filename="source patch")
            m.attach(a)
        if self.addLogs:
            for log in build.getLogs():
                name = "%s.%s" % (log.getStep().getName(),
                                  log.getName())
                if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name):
                    a = MIMEText(log.getText())
                    a.add_header('Content-Disposition', "attachment",
                                 filename=name)
                    m.attach(a)

        # Add any extra headers that were requested, doing WithProperties
        # interpolation if necessary
        if self.extraHeaders:
            for k,v in self.extraHeaders.items():
                k = properties.render(k)
                if k in m:
                    twlog("Warning: Got header " + k + " in self.extraHeaders "
                          "but it already exists in the Message - "
                          "not adding it.")
                    continue
                m[k] = properties.render(v)

        # now, who is this message going to?
        dl = []
        recipients = []
        if self.sendToInterestedUsers and self.lookup:
            for u in build.getInterestedUsers():
                d = defer.maybeDeferred(self.lookup.getAddress, u)
                d.addCallback(recipients.append)
                dl.append(d)
        d = defer.DeferredList(dl)
        d.addCallback(self._gotRecipients, recipients, m)
        return d
Example #16
0
    def createEmail(self, msgdict, builderName, title, results, builds=None, patches=None, logs=None):
        text = msgdict["body"].encode(ENCODING)
        type = msgdict["type"]
        if "subject" in msgdict:
            subject = msgdict["subject"].encode(ENCODING)
        else:
            subject = self.subject % {
                "result": Results[results],
                "projectName": title,
                "title": title,
                "builder": builderName,
            }

        assert "\n" not in subject, "Subject cannot contain newlines"

        assert type in ("plain", "html"), "'%s' message type must be 'plain' or 'html'." % type

        if patches or logs:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type, ENCODING))
        else:
            m = Message()
            m.set_payload(text, ENCODING)
            m.set_type("text/%s" % type)

        m["Date"] = formatdate(localtime=True)
        m["Subject"] = subject
        m["From"] = self.fromaddr
        # m['To'] is added later

        if patches:
            for (i, patch) in enumerate(patches):
                a = self.patch_to_attachment(patch, i)
                m.attach(a)
        if logs:
            for log in logs:
                name = "%s.%s" % (log.getStep().getName(), log.getName())
                if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name):
                    text = log.getText()
                    if not isinstance(text, unicode):
                        # guess at the encoding, and use replacement symbols
                        # for anything that's not in that encoding
                        text = text.decode(LOG_ENCODING, "replace")
                    a = MIMEText(text.encode(ENCODING), _charset=ENCODING)
                    a.add_header("Content-Disposition", "attachment", filename=name)
                    m.attach(a)

        # @todo: is there a better way to do this?
        # Add any extra headers that were requested, doing WithProperties
        # interpolation if only one build was given
        if self.extraHeaders:
            if len(builds) == 1:
                d = builds[0].render(self.extraHeaders)
            else:
                d = defer.succeed(self.extraHeaders)

            @d.addCallback
            def addExtraHeaders(extraHeaders):
                for k, v in extraHeaders.items():
                    if k in m:
                        twlog.msg(
                            "Warning: Got header " + k + " in self.extraHeaders "
                            "but it already exists in the Message - "
                            "not adding it."
                        )
                    m[k] = v

            d.addCallback(lambda _: m)
            return d

        return defer.succeed(m)
Example #17
0
    def buildMessage(self, name, build, results):
        if self.customMesg:
            # the customMesg stuff can be *huge*, so we prefer not to load it
            attrs = self.getCustomMesgData(self.mode, name, build, results, self.master_status)
            text, type = self.customMesg(attrs)
            msgdict = { 'body' : text, 'type' : type }
        elif self.messageFormatter:
            msgdict = self.messageFormatter(self.mode, name, build, results, self.master_status)
        else:
            msgdict = self.defaultMessage(self.mode, name, build, results, self.master_status)

        text = msgdict['body']
        type = msgdict['type']
        if 'subject' in msgdict:
            subject = msgdict['subject']
        else:
            subject = self.subject % { 'result': Results[results],
                                       'projectName': self.master_status.getProjectName(),
                                       'builder': name,
                                       }


        assert type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type

        haveAttachments = False
        ss = build.getSourceStamp()
        if (ss and ss.patch and self.addPatch) or self.addLogs:
            haveAttachments = True
            if not canDoAttachments:
                twlog.msg("warning: I want to send mail with attachments, "
                          "but this python is too old to have "
                          "email.MIMEMultipart . Please upgrade to python-2.3 "
                          "or newer to enable addLogs=True")

        if haveAttachments and canDoAttachments:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type))
        else:
            m = Message()
            m.set_payload(text)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = subject
        m['From'] = self.fromaddr
        # m['To'] is added later

        if ss and ss.patch and self.addPatch:
            patch = ss.patch
            a = MIMEText(patch[1])
            a.add_header('Content-Disposition', "attachment",
                         filename="source patch")
            m.attach(a)
        if self.addLogs:
            for log in build.getLogs():
                name = "%s.%s" % (log.getStep().getName(),
                                  log.getName())
                if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name):
                    a = MIMEText(log.getText())
                    a.add_header('Content-Disposition', "attachment",
                                 filename=name)
                    m.attach(a)

        # Add any extra headers that were requested, doing WithProperties
        # interpolation if necessary
        if self.extraHeaders:
            for k,v in self.extraHeaders.items():
                k = properties.render(k)
                if k in m:
                    twlog("Warning: Got header " + k + " in self.extraHeaders "
                          "but it already exists in the Message - "
                          "not adding it.")
                    continue
                m[k] = properties.render(v)

        # now, who is this message going to?
        dl = []
        recipients = []
        if self.sendToInterestedUsers and self.lookup:
            for u in build.getInterestedUsers():
                d = defer.maybeDeferred(self.lookup.getAddress, u)
                d.addCallback(recipients.append)
                dl.append(d)
        d = defer.DeferredList(dl)
        d.addCallback(self._gotRecipients, recipients, m)
        return d