Example #1
0
    def send_message(self, subject, message, attachments=None):
        '''Sends an alert message'''

        # We need to generate the message headers
        mime_msg = MIMEMultipart()
        mime_msg['From'] = self.config.mail_from
        mime_msg['To'] = self.value
        mime_msg['Subject'] = subject
        body = message
        mime_msg.attach(MIMEText(body, 'plain'))

        if attachments is not None:
            for attachment in attachments:
                part = MIMEBase('application', "octet-stream")
                part.set_payload(attachment[0])
                encoders.encode_base64(part)

                # Add attachment header to this MIME part
                part[
                    'Content-Disposition'] = 'attachment; filename="%s"' % attachment[
                        1]
                mime_msg.attach(part)

            message = mime_msg.__str__()  # Required to get UTF-8 email

        if self.config.smime_enabled is True:
            # OpenSSL will generate the message headers
            message = self.sign_email(subject, message)

        if self.method == ContactMethods.EMAIL:
            if self.config.smtp_disabled:
                self.config.logger.info("Would send message to %s", self.value)
                # Mail is disabled, just return
                return

            # And send it on its way
            self.config.logger.info("Sending message to %s", self.value)
            try:
                smtp_server = smtplib.SMTP(self.config.smtp_host)
                smtp_server.starttls()
                if self.config.smtp_username is not None:
                    smtp_server.login(self.config.smtp_username,
                                      self.config.smtp_password)
                smtp_server.sendmail(self.config.mail_from, self.value,
                                     bytes(message, 'utf-8'))
            except (smtplib.SMTPException, ConnectionError):
                self.config.logger.error(
                    "Unable to send email to %s due to %s", self.value,
                    sys.exc_info()[0])
            finally:
                smtp_server.quit()

        elif self.method == ContactMethods.FILE:
            with open(self.value, 'w') as contact_file:
                contact_file.write(message)
        else:
            raise ValueError('Unknown contact method!')
Example #2
0
    def sender(self, to=None, subject=None, contents=None, attachments=None):
        if to is None:
            raise ValueError("Please specify the email address to send")

        if isinstance(to, str):
            to = [to]

        if isinstance(to, list) is False:
            raise ValueError("Received mail type error")

        if subject is None:
            subject = 'Unit Test Report'
        if contents is None:
            contents = env.get_template('mail.html').render(
                mail_pass=str(RunResult.passed),
                mail_fail=str(RunResult.failed),
                mail_error=str(RunResult.errors),
                mail_skip=str(RunResult.skipped))

        msg = MIMEMultipart()
        msg['Subject'] = Header(subject, 'utf-8')
        msg['From'] = self.user
        msg['To'] = ",".join(to)

        text = MIMEText(contents, 'html', 'utf-8')
        msg.attach(text)

        if attachments is None:
            attachments = BrowserConfig.REPORT_PATH

        att_name = "report.html"
        if "\\" in attachments:
            att_name = attachments.split("\\")[-1]
        if "/" in attachments:
            att_name = attachments.split("/")[-1]

        att = MIMEApplication(open(attachments, 'rb').read())
        att['Content-Type'] = 'application/octet-stream'
        att["Content-Disposition"] = 'attachment; filename="{}"'.format(
            att_name)
        msg.attach(att)

        smtp = smtplib.SMTP_SSL(self.host, self.port)
        try:
            smtp.login(self.user, self.password)
            smtp.sendmail(self.user, to, msg.as_string())
            log.info(" 📧 Email sent successfully!!")
        except BaseException as msg:
            log.error('❌ Email failed to send!!' + msg.__str__())
        finally:
            smtp.quit()
Example #3
0
        def packUserdata(userdataList):
            if len(userdataList) == 1:
                return userdataList[0]

            combined_message = MIMEMultipart()
            for userdata in userdataList:
                userdata = userdata.strip()
                msg = email.message_from_file(c.StringIO(userdata))
                for part in msg.walk():
                    if part.get_content_maintype() == 'multipart':
                        continue
                    combined_message.attach(part)

            return combined_message.__str__()