示例#1
0
    def _setup_smtp(self, payload):
        """
        Setup smtp to send out a group of emails.
        """
        namespace = payload.get('namespace', 'splunk_app_infrastructure')
        sessionKey = payload.get('session_key')
        self.ssContent = self.ssContent if self.ssContent else self.getAlertActions(sessionKey, namespace)
        use_ssl = normalizeBoolean(self.ssContent.get('use_ssl', False))
        use_tls = normalizeBoolean(self.ssContent.get('use_tls', False))
        server = self.ssContent.get('mailserver', 'localhost')
        username = self.ssContent.get('auth_username', '')
        password = self.ssContent.get('clear_password', '')

        # setup the Open SSL Context
        sslHelper = ssl_context.SSLHelper()
        serverConfJSON = sslHelper.getServerSettings(sessionKey)
        # Pass in settings from alert_actions.conf into context
        ctx = sslHelper.createSSLContextFromSettings(
            sslConfJSON=self.ssContent,
            serverConfJSON=serverConfJSON,
            isClientContext=True)

        # send the mail
        if not use_ssl:
            smtp = secure_smtplib.SecureSMTP(host=server)
        else:
            smtp = secure_smtplib.SecureSMTP_SSL(host=server, sslContext=ctx)
        # smtp.set_debuglevel(1)
        if use_tls:
            smtp.starttls(ctx)
        if len(username) > 0 and len(password) > 0:
            smtp.login(username, password)
        return smtp
def send_mail_screenshot(settings, payload, session_key, file_type):
    '''
    Setup connection, attach file to mail and send out mail
    '''
    # Get Mail object
    email = build_email_object(settings, payload)
    email.attach(build_mime_attachment(file_type))
    
    sender     = email['From']
    use_ssl    = normalizeBoolean(settings.get('.use_ssl', False))
    use_tls    = normalizeBoolean(settings.get('use_tls', False))
    server     = settings.get('mailserver', 'localhost')

    username   = settings.get('auth_username', '')
    password   = settings.get('clear_password', '')
    recipients = []

    if email['To']:
        recipients.extend(EMAIL_DELIM.split(email['To']))

    # Clear leading / trailing whitespace from recipients
    recipients = [r.strip() for r in recipients]

    mail_log_msg = 'Sending email. subject="%s", recipients="%s", server="%s"' % (
        email['subject'],
        str(recipients),
        str(server)
    )

    try:
        # make sure the sender is a valid email address
        if sender.find("@") == -1:
            sender = sender + '@' + socket.gethostname()
            if sender.endswith("@"):
              sender = sender + 'localhost'

        # setup the Open SSL Context
        sslHelper = ssl_context.SSLHelper()
        serverConfJSON = sslHelper.getServerSettings(session_key)
        # Pass in settings from alert_actions.conf into context
        # Version 6.6
        
        try:
            ctx = sslHelper.createSSLContextFromSettings(
                sslConfJSON=settings,   # TODO: Check for error because this must be commented to work on customer site 
                serverConfJSON=serverConfJSON,
                isClientContext=True)
        except Exception, e:
            print >> sys.stderr, "WARN Setting up SSL context with Splunk > 6.5.x version not possible: %s" % e
            try:
            # Version 6.4
                ctx = sslHelper.createSSLContextFromSettings(
                    confJSON=settings,
                    sessionKey=session_key,
                    isClientContext=True)
            except Exception, e:
                print >> sys.stderr, "WARN Setting up SSL context with Splunk < 6.6.x version not possible: %s" % e
                raise
示例#3
0
    def _setup_smtp(self, payload):
        """
        Setup smtp to send out a group of emails.
        """
        use_ssl = normalizeBoolean(self.ssContent.get('use_ssl', False))
        use_tls = normalizeBoolean(self.ssContent.get('use_tls', False))
        server = self.ssContent.get('mailserver', 'localhost')
        username = self.ssContent.get('auth_username', '')
        password = self.ssContent.get('clear_password', '')

        # setup the Open SSL Context
        sslHelper = ssl_context.SSLHelper()
        serverConfJSON = sslHelper.getServerSettings(self.sessionKey)
        # Pass in settings from alert_actions.conf into context
        ctx = sslHelper.createSSLContextFromSettings(
            sslConfJSON=self.ssContent,
            serverConfJSON=serverConfJSON,
            isClientContext=True)

        # send the mail
        if not use_ssl:
            smtp = secure_smtplib.SecureSMTP(host=server)
        else:
            smtp = secure_smtplib.SecureSMTP_SSL(host=server, sslContext=ctx)
        # smtp.set_debuglevel(1)
        if use_tls:
            smtp.starttls(ctx)

        if username and password and username.strip() and password.strip():
            try:
                smtp.login(username, password)
            except SMTPAuthenticationError as e:
                logger.error('Email server: fail to authenticate: %s' % e)
            except SMTPHeloError as e:
                logger.error('Email server: fail to reply to hello: %s' % e)
            except SMTPException as e:
                logger.error(
                    'Email server: fail to find suitable authentication method: %s'
                    % e)
        else:
            logger.warning(
                'Email server: using unauthenticated connection to SMTP server'
            )

        return smtp
    def handleCreate(self, confInfo):
        message = MIMEMultipart()

        subject = self.gfa('subject')
        body = self.gfa('body')
        bodyformat = self.gfa('format', 'html')

        server = self.gfa('server', 'localhost')

        username = self.gfa('username')
        password = self.gfa('password')

        use_ssl = toBool(self.gfa('use_ssl'))
        use_tls = toBool(self.gfa('use_tls'))

        sessionKey = self.getSessionKey()

        sslSettings = self.getAlertActions(sessionKey)

        # Open debate whether we should get user and password from alert actions
        # username = sslSettings.get('auth_username', '')
        # password = sslSettings.get('clear_password', '')

        if isASCII(subject):
            message['Subject'] = subject
        else:
            message['Subject'] = Header(subject, charset)

        recipients = []
        for t in self.callerArgs.get('to'):
            recipients.append(t.strip())
        message['To'] = ', '.join(self.callerArgs.get('to'))

        if self.hasNonEmptyArg('cc'):
            cc = [x for x in self.callerArgs.get('cc') if x != None]
            if len(cc) > 0:
                message['Cc'] = ', '.join(cc)
                for t in cc:
                    recipients.append(t.strip())

        if self.hasNonEmptyArg('bcc'):
            bcc = [x for x in self.callerArgs.get('bcc') if x != None]
            if len(bcc) > 0:
                message['Bcc'] = ', '.join(bcc)
                for t in bcc:
                    recipients.append(t.strip())

        sender = 'splunk'
        if self.hasNonEmptyArg('from'):
            sender = self.gfa('from')

        if sender.find("@") == -1:
            sender = sender + '@' + socket.gethostname()
            if sender.endswith("@"):
                sender = sender + 'localhost'

        message['From'] = sender

        message.attach(MIMEText(body, bodyformat, _charset=charset))

        if use_ssl or use_tls:
            sslHelper = ssl_context.SSLHelper()
            # Pass in settings from alert_actions.conf into context
            ctx = sslHelper.createSSLContextFromSettings(confJSON=sslSettings,
                                                         sessionKey=sessionKey,
                                                         isClientContext=True)

        # send the mail
        if not use_ssl:
            smtp = secure_smtplib.SecureSMTP(host=server)
        else:
            smtp = secure_smtplib.SecureSMTP_SSL(host=server, sslContext=ctx)

        if use_tls:
            smtp.starttls(ctx)
        if len(username) > 0 and len(password) > 0:
            smtp.login(username, password)

        smtp.sendmail(sender, recipients, message.as_string())
        smtp.quit()