Ejemplo n.º 1
0
    def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', _callback=None):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                                % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if _callback:
            _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)
        dfd = self._sendmail(rcpts, msg.as_string())
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
                         callbackArgs=[to, cc, subject, len(attachs)],
                         errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd
Ejemplo n.º 2
0
    def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain',body_encode='utf8'):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body, 'plain', body_encode))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        try:
            self._sendmail(rcpts, msg.as_string())
        except smtplib.SMTPException, e:
            self._sent_failed(e, to, cc, subject, len(attachs))
            return False
Ejemplo n.º 3
0
Archivo: mail.py Proyecto: 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
Ejemplo n.º 4
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
Ejemplo n.º 5
0
    def send(self, to, subject, body, cc=None, attachs=()):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart('text', 'plain')
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if self.signals:
            self.signals.send_catch_log(signal=mail_sent,
                                        to=to,
                                        subject=subject,
                                        body=body,
                                        cc=cc,
                                        attach=attachs,
                                        msg=msg)

        if self.debug:
            log.msg(
                format=
                'Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s Subject="%(mailsubject)s" Attachs=%(mailattachs)d',
                level=log.DEBUG,
                mailto=to,
                mailcc=cc,
                mailsubject=subject,
                mailattachs=len(attachs))
            return

        dfd = self._sendmail(rcpts, msg.as_string())
        dfd.addCallbacks(self._sent_ok,
                         self._sent_failed,
                         callbackArgs=[to, cc, subject,
                                       len(attachs)],
                         errbackArgs=[to, cc, subject,
                                      len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd
Ejemplo n.º 6
0
def sendMail(subject,
             body,
             attachments = [],
             status = False,
             from_mail = '*****@*****.**',
             to_mail = [ '*****@*****.**' ],
             smtp_host = ''):
    if attachments:
        msg = MIMEMultipart()
    else:
        msg = Message()

    msg['Subject'] = subject
    msg['From']    = from_mail
    msg['To']      = ', '.join(to_mail)
    msg['X-ERP5-Tests'] = 'ERP5'

    if status:
        msg['X-ERP5-Tests-Status'] = 'OK'

    # Guarantees the message ends in a newline
    msg.preamble = subject
    msg.epilogue = ''

    if attachments:
        mime_text = MIMEText(body)
        mime_text.add_header('Content-Disposition', 'attachment',
                             filename='body')
        msg.attach(mime_text)
        html_re = re.compile('<html>', re.I)
        for item in attachments:
            mime_text = MIMEText(item)
            if html_re.match(item):
                mime_text.set_type('text/html')
                mime_text.add_header('Content-Disposition', 'attachment',
                                     filename='attachment.html')
            else:
                mime_text.add_header('Content-Disposition', 'attachment',
                                     filename='attachment.txt')
            msg.attach(mime_text)

    else:
        msg.set_payload(body)

    # Send the email via SMTP server.
    if smtp_host:
      s = smtplib.SMTP(smtp_host)
    else:
      s = smtplib.SMTP()
      s.connect()
    s.sendmail(from_mail, to_mail, msg.as_string())
    s.close()
Ejemplo n.º 7
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
    def _convert_to_mbox_msg(self, msg):
        file_ids = list(msg.objectIds('File'))
        encoding = "utf-8"

        # true only if we have attachments
        if file_ids:
            enc_msg = MIMEMultipart()
            txt = MIMEText(msg.body.encode(encoding))
            enc_msg.attach(txt)
        else:
            enc_msg = Message()
            enc_msg.set_payload(msg.body.encode(encoding))

        enc_msg['From'] = encode_header(msg.from_addr, encoding)
        enc_msg['To'] = encode_header(self.context.mailto, encoding)
        enc_msg['Subject'] = encode_header(msg.subject, encoding).replace("\n", " ").strip()
        enc_msg['Date'] = encode_header(str(msg.date), encoding)
        enc_msg['Message-id'] = encode_header(msg.message_id, encoding)
        if msg.references:
            enc_msg['References'] = encode_header(" ".join(msg.references), encoding)
        if msg.in_reply_to:
            enc_msg['In-reply-to'] = encode_header(msg.in_reply_to, encoding)
                                    
        ctime = str(msg.date)
        enc_msg.set_unixfrom("From %s %s" % (parseaddr(msg.from_addr)[1], ctime))

        for file_id in file_ids:
            file = msg._getOb(file_id)
            data = file.data
            if not isinstance(data, basestring):
                data = str(data)
            content_type = file.getContentType()
            if content_type == 'message/rfc822':
                attachment = message_from_string(data)
            else:
                attachment = Message()
                attachment.add_header('Content-Disposition', 'attachment', filename=file.title)
                attachment.add_header('Content-Type', content_type)
                attachment.set_payload(data)
            enc_msg.attach(attachment)

        try:
            retval = enc_msg.as_string(unixfrom=True)
        except TypeError, e:
            raise
Ejemplo n.º 9
0
    def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', _callback=None):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"'
                                % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if _callback:
            _callback(
                to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)

        if self.debug:
            log.msg(format='Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s Subject="%(mailsubject)s" Attachs=%(mailattachs)d',
                    level=log.DEBUG, mailto=to, mailcc=cc, mailsubject=subject, mailattachs=len(attachs))
            return

        dfd = self._sendmail(rcpts, msg.as_string())
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
                         callbackArgs=[to, cc, subject, len(attachs)],
                         errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd
Ejemplo n.º 10
0
    def send(self, to, subject, body, cc=None, attachs=()):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart('text', 'plain')
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        send_catch_log(signal=mail_sent, to=to, subject=subject, body=body,
                       cc=cc, attach=attachs, msg=msg)

        if settings.getbool('MAIL_DEBUG'):
            log.msg('Debug mail sent OK: To=%s Cc=%s Subject="%s" Attachs=%d' % \
                (to, cc, subject, len(attachs)), level=log.DEBUG)
            return

        dfd = self._sendmail(rcpts, msg.as_string())
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
            callbackArgs=[to, cc, subject, len(attachs)],
            errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd
Ejemplo n.º 11
0
    def send(self, to, subject, body, cc=None, attachs=()):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart('text', 'plain')
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        # FIXME ---------------------------------------------------------------------
        # There seems to be a problem with sending emails using deferreds when
        # the last thing left to do is sending the mail, cause the engine stops
        # the reactor and the email don't get send. we need to fix this. until
        # then, we'll revert to use Python standard (IO-blocking) smtplib.

        #dfd = self._sendmail(self.smtphost, self.mailfrom, rcpts, msg.as_string())
        #dfd.addCallbacks(self._sent_ok, self._sent_failed,
        #    callbackArgs=[to, cc, subject, len(attachs)],
        #    errbackArgs=[to, cc, subject, len(attachs)])
        import smtplib
        smtp = smtplib.SMTP(self.smtphost)
        smtp.sendmail(self.mailfrom, rcpts, msg.as_string())
        log.msg('Mail sent: To=%s Cc=%s Subject="%s"' % (to, cc, subject))
        smtp.close()
Ejemplo n.º 12
0
    def send(self,
             to,
             subject,
             body,
             cc=None,
             attachs=(),
             mimetype='text/plain',
             body_encode='utf8'):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))
        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if attachs:
            msg.attach(MIMEText(body, 'plain', body_encode))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        try:
            self._sendmail(rcpts, msg.as_string())
        except smtplib.SMTPException, e:
            self._sent_failed(e, to, cc, subject, len(attachs))
            return False
Ejemplo n.º 13
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
Ejemplo n.º 14
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
Ejemplo n.º 15
0
        else:
            print("checked email, but did not have an sln number at time %s" % time.ctime())


try:
    data = json.loads(open('../personal_data.json').read())
    # M = imaplib2.IMAP4_SSL('imap-mail.outlook.com')# times out after about 3 minutes on hotmail account, gmail does not
    M = imaplib2.IMAP4_SSL('imap.gmail.com')
    M.login(data["gmail"], data["gmail_password"])
    M.select("INBOX")
    # adds am email to the mailbox
    msg = MIMEMultipart()
    msg["From"] = data["email"]
    msg["Subject"] = "Appended Email"
    msg.set_payload("First Appended Email")
    M.append('INBOX', '', imaplib2.Time2Internaldate(time.time()), str(msg))
    print("Waiting for Emails....")
    print("Press ctrl + c to stop")
    idler = Idler(M)  # Start the Idler thread
    idler.start()
    slns = []
    while True:
        driver = webdriver.Firefox()  # open browser to wait for email
        driver.get("https://sdb.admin.uw.edu/students/uwnetid/register.asp")
        assert "NetID" in driver.title
        elem = driver.find_element_by_name("user")
        elem.send_keys(data["uw_username"])
        elem = driver.find_element_by_name("pass")
        elem.send_keys(data["uw_password"])
        elem.send_keys(Keys.RETURN)
Ejemplo n.º 16
0
Archivo: mail.py Proyecto: 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
Ejemplo n.º 17
0
    def buildMessage(self, name, build, results):
        projectName = self.status.getProjectName()
        text = ""
        if self.mode == "all":
            text += "The Buildbot has finished a build"
        elif self.mode == "failing":
            text += "The Buildbot has detected a failed build"
        else:
            text += "The Buildbot has detected a new failure"
        text += " of %s on %s.\n" % (name, projectName)
        buildurl = self.status.getURLForThing(build)
        if buildurl:
            text += "Full details are available at:\n %s\n" % buildurl
        text += "\n"

        url = self.status.getBuildbotURL()
        if url:
            text += "Buildbot URL: %s\n\n" % urllib.quote(url, "/:")

        text += "Buildslave for this Build: %s\n\n" % build.getSlavename()
        text += "Build Reason: %s\n" % build.getReason()

        patch = None
        ss = build.getSourceStamp()
        if ss is None:
            source = "unavailable"
        else:
            source = ""
            if ss.branch:
                source += "[branch %s] " % ss.branch
            if ss.revision:
                source += ss.revision
            else:
                source += "HEAD"
            if ss.patch is not None:
                source += " (plus patch)"
                patch = ss.patch
        text += "Build Source Stamp: %s\n" % source

        text += "Blamelist: %s\n" % ",".join(build.getResponsibleUsers())

        # TODO: maybe display changes here? or in an attachment?
        text += "\n"

        t = build.getText()
        if t:
            t = ": " + " ".join(t)
        else:
            t = ""

        if results == SUCCESS:
            text += "Build succeeded!\n"
            res = "success"
        elif results == WARNINGS:
            text += "Build Had Warnings%s\n" % t
            res = "warnings"
        else:
            text += "BUILD FAILED%s\n" % t
            res = "failure"

        if self.addLogs and build.getLogs():
            text += "Logs are attached.\n"

        # TODO: it would be nice to provide a URL for the specific build
        # here. That involves some coordination with html.Waterfall .
        # Ideally we could do:
        #  helper = self.parent.getServiceNamed("html")
        #  if helper:
        #      url = helper.getURLForBuild(build)

        text += "\n"
        text += "sincerely,\n"
        text += " -The Buildbot\n"
        text += "\n"

        haveAttachments = False
        if 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))
        else:
            m = Message()
            m.set_payload(text)

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

        if patch:
            a = MIMEText(patch)
            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())
                a = MIMEText(log.getText())
                a.add_header("Content-Disposition", "attachment", filename=name)
                m.attach(a)

        # now, who is this message going to?
        dl = []
        recipients = self.extraRecipients[:]
        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
 print recv1
 a = []
 while b:
     mes = raw_input()
     if mes != ".":
         # In case the user decides to send an attachment the following action is taken. The attachement can be a textfile or an 				image
         if mes == "att" or mes == "ATT":
             print "Type 1 to send a .txt file\n"
             print "Type 2 to send a .png file\n"
             gh = raw_input()
             # incase the user wants to send a *.txt file
             if gh == "1":
                 msg = MIMEMultipart()
                 print "Type the complete path of your file including your file name"
                 gh = raw_input()
                 msg.set_payload(file(gh).read())
                 email.encoders.encode_base64(msg)
                 a.append(msg.as_string())
                 # incase the user wants to send a *.png file
             else:
                 msg = MIMEMultipart()
                 print "Type the complete path of your file including the extension"
                 gh = raw_input()
                 img = MIMEImage(open(gh, "rb").read(), _subtype="png")
                 img.add_header("Content-Disposition", 'attachment; filename="test image"')
                 msg.attach(img)
                 a.append(msg.as_string())
                 # Else case where the user decides to send a plain message which is to be typed in the terminal
         else:
             a.append(mes)
             # The following segment of code indicates the action to be taken when the user ends the message with a period
Ejemplo n.º 19
0
    def buildMessage(self, name, build, results):
        projectName = self.status.getProjectName()
        text = ""
        if self.mode == "all":
            text += "The Buildbot has finished a build"
        elif self.mode == "failing":
            text += "The Buildbot has detected a failed build"
        else:
            text += "The Buildbot has detected a new failure"
        text += " of %s on %s.\n" % (name, projectName)
        buildurl = self.status.getURLForThing(build)
        if buildurl:
            text += "Full details are available at:\n %s\n" % buildurl
        text += "\n"

        url = self.status.getBuildbotURL()
        if url:
            text += "Buildbot URL: %s\n\n" % urllib.quote(url, '/:')

        text += "Buildslave for this Build: %s\n\n" % build.getSlavename()
        text += "Build Reason: %s\n" % build.getReason()

        patch = None
        ss = build.getSourceStamp()
        if ss is None:
            source = "unavailable"
        else:
            source = ""
            if ss.branch:
                source += "[branch %s] " % ss.branch
            if ss.revision:
                source += ss.revision
            else:
                source += "HEAD"
            if ss.patch is not None:
                source += " (plus patch)"
                patch = ss.patch
        text += "Build Source Stamp: %s\n" % source

        text += "Blamelist: %s\n" % ",".join(build.getResponsibleUsers())

        # TODO: maybe display changes here? or in an attachment?
        text += "\n"

        t = build.getText()
        if t:
            t = ": " + " ".join(t)
        else:
            t = ""

        if results == SUCCESS:
            text += "Build succeeded!\n"
            res = "success"
        elif results == WARNINGS:
            text += "Build Had Warnings%s\n" % t
            res = "warnings"
        else:
            text += "BUILD FAILED%s\n" % t
            res = "failure"

        if self.addLogs and build.getLogs():
            text += "Logs are attached.\n"

        # TODO: it would be nice to provide a URL for the specific build
        # here. That involves some coordination with html.Waterfall .
        # Ideally we could do:
        #  helper = self.parent.getServiceNamed("html")
        #  if helper:
        #      url = helper.getURLForBuild(build)

        text += "\n"
        text += "sincerely,\n"
        text += " -The Buildbot\n"
        text += "\n"

        haveAttachments = False
        if 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))
        else:
            m = Message()
            m.set_payload(text)

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

        if patch:
            a = MIMEText(patch)
            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())
                a = MIMEText(log.getText())
                a.add_header('Content-Disposition', "attachment",
                             filename=name)
                m.attach(a)

        # now, who is this message going to?
        dl = []
        recipients = self.extraRecipients[:]
        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
Ejemplo n.º 20
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
Ejemplo n.º 21
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
Ejemplo n.º 22
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
Ejemplo n.º 23
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)
Ejemplo n.º 24
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