コード例 #1
0
 def send(self):
     if (not sesEmail.isLocal):
         # Use aws creds for ses if possible, otherwise, use aws_key from config
         connection = boto.connect_ses()
         try:
             return connection.send_email(self.fromAddress,
                                          self.subject,
                                          self.content,
                                          self.toAddress,
                                          format='html')
         except:
             connection = boto.connect_ses(
                 aws_access_key_id=CONFIG_BROKER['aws_access_key_id'],
                 aws_secret_access_key=CONFIG_BROKER[
                     'aws_secret_access_key'])
             return connection.send_email(self.fromAddress,
                                          self.subject,
                                          self.content,
                                          self.toAddress,
                                          format='html')
     else:
         newEmailText = "\n\n".join([
             "", "Time",
             str(datetime.datetime.now()), "Subject", self.subject, "From",
             self.fromAddress, "To", self.toAddress, "Content", self.content
         ])
         open(sesEmail.emailLog, "a").write(newEmailText)
コード例 #2
0
ファイル: util.py プロジェクト: rsniezynski/sea-cucumber
def get_boto_ses_connection():
    """
    Shortcut for instantiating and returning a boto SESConnection object.

    :rtype: boto.ses.SESConnection
    :returns: A boto SESConnection object, from which email sending is done.
    """

    access_key_id = getattr(
        settings, 'CUCUMBER_SES_ACCESS_KEY_ID',
        getattr(settings, 'AWS_ACCESS_KEY_ID', None))
    access_key = getattr(
        settings, 'CUCUMBER_SES_SECRET_ACCESS_KEY',
        getattr(settings, 'AWS_SECRET_ACCESS_KEY', None))

    return boto.connect_ses(
        aws_access_key_id=access_key_id,
        aws_secret_access_key=access_key,
        region=get_ses_region()
    )
    region_name = getattr(
        settings, 'CUCUMBER_SES_REGION_NAME',
        getattr(settings, 'AWS_SES_REGION_NAME', None))

    if region_name != None:
        return boto.ses.connect_to_region(
            region_name,
            aws_access_key_id=access_key_id,
            aws_secret_access_key=access_key,
        )
    else:
        return boto.connect_ses(
            aws_access_key_id=access_key_id,
            aws_secret_access_key=access_key,
        )
コード例 #3
0
 def send(self):
     if(not sesEmail.isLocal):
         # Use aws creds for ses if possible, otherwise, use aws_key from config
         connection = boto.connect_ses()
         try:
             return connection.send_email(self.fromAddress, self.subject,self.content,self.toAddress,format='html')
         except:
             connection = boto.connect_ses(aws_access_key_id=CONFIG_BROKER['aws_access_key_id'], aws_secret_access_key=CONFIG_BROKER['aws_secret_access_key'])
             return connection.send_email(self.fromAddress, self.subject,self.content,self.toAddress,format='html')
     else:
         newEmailText = "\n\n".join(["","Time",str(datetime.datetime.now()),"Subject",self.subject,"From",self.fromAddress,"To",self.toAddress,"Content",self.content])
         open (sesEmail.emailLog,"a").write(newEmailText)
コード例 #4
0
ファイル: ses_handler.py プロジェクト: fayazkhan/ses_handler
 def __init__(self, sender='', recipients=[], subject='', level=NOTSET):
     super(SESHandler, self).__init__(level)
     self._ses_connection = boto.connect_ses()
     self._sender = sender
     self._recipients = recipients
     self._subject = subject
     self.limit_exceeded = False
コード例 #5
0
 def _send_email(self, mails, subject, body):
     if mails:
         import boto
         ses = boto.connect_ses(self.read_option('access_key'),
                                self.read_option('secret_key'))
         ses.send_email(self.read_option('mail_from', DEFAULT_MAIN_FROM),
                        subject, body, mails)
コード例 #6
0
def send_ses(fromaddr,
             subject,
             body,
             recipient,
             attachment=None,
             filename=''):
    """Send an email via the Amazon SES service.

    Example:
      send_ses('[email protected], 'greetings', "Hi!", '[email protected])

    Return:
      If 'ErrorResponse' appears in the return message from SES,
      return the message, otherwise return an empty '' string.
    """
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = fromaddr
    msg['To'] = recipient
    msg.attach(MIMEText(body))
    
    if attachment:
        part = MIMEApplication(attachment)
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(part)
    conn = boto.connect_ses()
    result = conn.send_raw_email(msg.as_string())
    return result if 'ErrorResponse' in result else ''
コード例 #7
0
def send_mail(send_to, subject, mail_body, file_name='no'):
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = '*****@*****.**'
    msg['To'] = send_to

    # what a recipient sees if they don't use an email reader
    msg.preamble = 'Multipart message.\n'

    # the message body
    part = MIMEText(mail_body)
    msg.attach(part)

    # the attachment
    if file_name != 'no':
        part = MIMEApplication(open(file_name, 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename=file_name)
        msg.attach(part)

    # connect to SES
    aws_access_key_id = 'AKIAIPT74FHV5KIH6CBA'
    aws_access_key_secret = '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'
    connection = boto.connect_ses(aws_access_key_id, aws_access_key_secret)

    # and send the message
    result = connection.send_raw_email(msg.as_string(), source=msg['From'], destinations=[msg['To']])
    print result
コード例 #8
0
ファイル: __init__.py プロジェクト: psmit/volunteer
def send_email(mailaddress,subject,message,settings,prefix="aws."):
    from_email = "*****@*****.**"

    connection = boto.connect_ses(settings[prefix+'access_key_id'],
                                  settings[prefix+'secret_access_key'])

    connection.send_email(from_email,subject,message,[mailaddress])
コード例 #9
0
def test_delete_identity():
    conn = boto.connect_ses('the_key', 'the_secret')
    conn.verify_email_identity("*****@*****.**")

    conn.list_identities()['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'].should.have.length_of(1)
    conn.delete_identity("*****@*****.**")
    conn.list_identities()['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'].should.have.length_of(0)
コード例 #10
0
ファイル: mailer.py プロジェクト: heikkiv/flashback
def send_email(today, source, recipients, dates_and_urls, id_and_secret):
    msg = MIMEMultipart()
    msg["Subject"] = Header(u"Tapahtui %d.%d." % (today[2], today[1]), "utf-8")
    msg["From"] = source
    msg["To"] = ", ".join(recipients)

    # what a recipient sees if they don't use an email reader
    msg.preamble = "This is a multi-part message in MIME format.\n"

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msg_alternative = MIMEMultipart("alternative")
    msg.attach(msg_alternative)

    msg_text = MIMEText("This is the alternative plain text message.")
    msg_alternative.attach(msg_text)

    # the pictures
    html = u""
    for date, url in dates_and_urls:
        html += u"<strong>%d.%d.%d</strong>" % (date[2], date[1], date[0])
        html += u'<br><br><img src="' + url + u'"><br><br>'

    # We reference the image in the IMG SRC attribute by the ID we give it below
    msg_text = MIMEText(html.encode("utf-8"), "html", "utf-8")
    msg_alternative.attach(msg_text)

    # connect to SES
    connection = boto.connect_ses(aws_access_key_id=id_and_secret[0], aws_secret_access_key=id_and_secret[1])

    # and send the message
    result = connection.send_raw_email(msg.as_string(), source=msg["From"], destinations=recipients)
    return result
コード例 #11
0
ファイル: ses_mailer.py プロジェクト: JelteF/ses-mailer
    def __init__(self,
                 aws_access_key_id=None,
                 aws_secret_access_key=None,
                 region="us-east-1",
                 sender=None,
                 reply_to=None,
                 template=None,
                 template_context={},
                 app=None):
        """
        Setup the mail

        """
        if app:
            self.init_app(app)
        else:
            if aws_access_key_id and aws_secret_access_key:
                if region:
                    self.ses = boto.ses.connect_to_region(region,
                                                          aws_access_key_id=aws_access_key_id,
                                                          aws_secret_access_key=aws_secret_access_key)
                else:
                    self.ses = boto.connect_ses(aws_access_key_id=aws_access_key_id,
                                                aws_secret_access_key=aws_secret_access_key)

            self.sender = sender
            self.reply_to = reply_to or self.sender

            if template:
                self.template = Template(template=template)
            if template_context:
                self.template_context = template_context
コード例 #12
0
def test_verify_email_identity():
    conn = boto.connect_ses('the_key', 'the_secret')
    conn.verify_email_identity("*****@*****.**")

    identities = conn.list_identities()
    address = identities['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'][0]
    address.should.equal('*****@*****.**')
コード例 #13
0
ファイル: test_ses.py プロジェクト: research-scife/moto
def test_get_send_statistics():
    conn = boto.connect_ses("the_key", "the_secret")

    conn.send_email.when.called_with(
        "*****@*****.**",
        "test subject",
        "<span>test body</span>",
        "*****@*****.**",
        format="html",
    ).should.throw(BotoServerError)

    # tests to verify rejects in get_send_statistics
    result = conn.get_send_statistics()

    reject_count = int(
        result["GetSendStatisticsResponse"]["SendDataPoints"][0]["Rejects"])
    delivery_count = int(result["GetSendStatisticsResponse"]["SendDataPoints"]
                         [0]["DeliveryAttempts"])
    reject_count.should.equal(1)
    delivery_count.should.equal(0)

    conn.verify_email_identity("*****@*****.**")
    conn.send_email("*****@*****.**", "test subject", "test body",
                    "*****@*****.**")

    # tests to delivery attempts in get_send_statistics
    result = conn.get_send_statistics()

    reject_count = int(
        result["GetSendStatisticsResponse"]["SendDataPoints"][0]["Rejects"])
    delivery_count = int(result["GetSendStatisticsResponse"]["SendDataPoints"]
                         [0]["DeliveryAttempts"])
    reject_count.should.equal(1)
    delivery_count.should.equal(1)
コード例 #14
0
ファイル: test_ses.py プロジェクト: DarthLorenzo/moto
def test_send_raw_email():
    conn = boto.connect_ses('the_key', 'the_secret')

    message = email.mime.multipart.MIMEMultipart()
    message['Subject'] = 'Test'
    message['From'] = '*****@*****.**'
    message['To'] = '*****@*****.**'

    # Message body
    part = email.mime.text.MIMEText('test file attached')
    message.attach(part)

    # Attachment
    part = email.mime.text.MIMEText('contents of test file here')
    part.add_header('Content-Disposition', 'attachment; filename=test.txt')
    message.attach(part)

    conn.send_raw_email.when.called_with(
        source=message['From'],
        raw_message=message.as_string(),
    ).should.throw(BotoServerError)

    conn.verify_email_identity("*****@*****.**")
    conn.send_raw_email(
        source=message['From'],
        raw_message=message.as_string(),
    )

    send_quota = conn.get_send_quota()
    sent_count = int(send_quota['GetSendQuotaResponse']['GetSendQuotaResult']['SentLast24Hours'])
    sent_count.should.equal(1)
コード例 #15
0
ファイル: test_ses.py プロジェクト: pj0616/moto_bpandola
def test_send_html_email():
    conn = boto.connect_ses("the_key", "the_secret")

    conn.send_email.when.called_with(
        "*****@*****.**",
        "test subject",
        "<span>test body</span>",
        "*****@*****.**",
        format="html",
    ).should.throw(BotoServerError)

    conn.verify_email_identity("*****@*****.**")
    conn.send_email(
        "*****@*****.**",
        "test subject",
        "<span>test body</span>",
        "*****@*****.**",
        format="html",
    )

    send_quota = conn.get_send_quota()
    sent_count = int(
        send_quota["GetSendQuotaResponse"]["GetSendQuotaResult"]["SentLast24Hours"]
    )
    sent_count.should.equal(1)
コード例 #16
0
ファイル: test_ses.py プロジェクト: DarthLorenzo/moto
def test_verify_email_identity():
    conn = boto.connect_ses('the_key', 'the_secret')
    conn.verify_email_identity("*****@*****.**")

    identities = conn.list_identities()
    address = identities['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'][0]
    address.should.equal('*****@*****.**')
コード例 #17
0
    def exception_email(self, exception):
        """
            Function to send email notifications
            """

        content = 'Hi Team, Canary Validation failed!!! Error message: ' \
                  + str(exception)

        # Setup subject for the email

        subject = self.env.upper() + ': Canary ' + self.validation_type \
                  + ' Validation Failed for ' + str(self.dag_name) + ' - ' \
                  + str(self.dag_exec_dt)

        # Email configuration

        msg = MIMEMultipart()
        msg['From'] = self.fromaddr
        #msg['To'] = ', '.join(self.toaddr)
        msg['Subject'] = subject
        content = content
        msg.attach(MIMEText(content, 'html'))
        text = msg.as_string()
        # connect to SES
        connection = boto.connect_ses()
        # and send the message
        result = connection.send_raw_email(text,
                                           source=msg['From'],
                                           destinations=self.toaddr)
コード例 #18
0
def send_ses(fromaddr, subject, body, recipient, attachment=None,
             filename=''):
    """Send an email via the Amazon SES service.

    Example:
      send_ses('[email protected], 'greetings', "Hi!", '[email protected])

    Return:
      If 'ErrorResponse' appears in the return message from SES,
      return the message, otherwise return an empty '' string.
    """
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = fromaddr
    msg['To'] = recipient
    msg.attach(MIMEText(body))
    if attachment:
        part = MIMEApplication(attachment)
        part.add_header('Content-Disposition', 'attachment',
                        filename=filename)
        msg.attach(part)
    conn = boto.connect_ses(aws_access_key_id=AWS_ACCESS_KEY_ID,
                            aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
    result = conn.send_raw_email(msg.as_string())
    return result if 'ErrorResponse' in result else ''
コード例 #19
0
ファイル: output.py プロジェクト: topiaruss/spray
 def __init__(self, overrides=None):
     self.overrides = overrides
     conf = aws_credentials.get_credentials()
     region = ses.regions()[0]  # Getting first region
     self.conn = boto.connect_ses(aws_access_key_id=conf[0],
       aws_secret_access_key=conf[1],
       region=region)
コード例 #20
0
def customer_registered():
    """Send an e-mail using SES"""

    response = None
    if request.json is None:
        # Expect application/json request
        response = Response("", status=415)
    else:
        message = dict()
        try:
            # If the message has an SNS envelope, extract the inner message
            if request.json.has_key('TopicArn') and request.json.has_key('Message'):
                message = json.loads(request.json['Message'])
            else:
                message = request.json
            
            # Connect to SES and send an e-mail    
            ses = boto.connect_ses()
            ses.send_email(source=application.config['SOURCE_EMAIL_ADDRESS'],
                           subject=SUBJECT,
                           body=BODY % (message['name']),
                           to_addresses=[message['email']])
            response = Response("", status=200)
        except Exception as ex:
            logging.exception('Error processing message: %s' % request.json)
            response = Response(ex.message, status=500)

    return response
コード例 #21
0
def customer_registered():
    """Send an e-mail using SES"""

    response = None
    if request.json is None:
        # Expect application/json request
        response = Response("", status=415)
    else:
        message = dict()
        try:
            # If the message has an SNS envelope, extract the inner message
            if request.json.has_key('TopicArn') and request.json.has_key(
                    'Message'):
                message = json.loads(request.json['Message'])
            else:
                message = request.json

            # Connect to SES and send an e-mail
            ses = boto.connect_ses()
            ses.send_email(source=application.config['SOURCE_EMAIL_ADDRESS'],
                           subject=SUBJECT,
                           body=BODY % (message['name']),
                           to_addresses=[message['email']])
            response = Response("", status=200)
        except Exception as ex:
            logging.exception('Error processing message: %s' % request.json)
            response = Response(ex.message, status=500)

    return response
コード例 #22
0
ファイル: test_ses.py プロジェクト: yurigo79/moto
def test_send_raw_email():
    conn = boto.connect_ses('the_key', 'the_secret')

    message = email.mime.multipart.MIMEMultipart()
    message['Subject'] = 'Test'
    message['From'] = '*****@*****.**'
    message['To'] = '*****@*****.**'

    # Message body
    part = email.mime.text.MIMEText('test file attached')
    message.attach(part)

    # Attachment
    part = email.mime.text.MIMEText('contents of test file here')
    part.add_header('Content-Disposition', 'attachment; filename=test.txt')
    message.attach(part)

    conn.send_raw_email.when.called_with(
        source=message['From'],
        raw_message=message.as_string(),
    ).should.throw(BotoServerError)

    conn.verify_email_identity("*****@*****.**")
    conn.send_raw_email(
        source=message['From'],
        raw_message=message.as_string(),
    )

    send_quota = conn.get_send_quota()
    sent_count = int(send_quota['GetSendQuotaResponse']['GetSendQuotaResult']
                     ['SentLast24Hours'])
    sent_count.should.equal(1)
コード例 #23
0
ファイル: scheduler.py プロジェクト: deepak64/scraper-test
def send_emails(opts, error_link):
    if SES_LOGIN:
        ses = boto.connect_ses(*SES_LOGIN)
        ses.send_email(EMAIL_FROM, EMAIL_SUBJECT % opts.spider,
            EMAIL_BODY % (opts.spider, error_link), opts.mail)
    else:
        print EMAIL_BODY % (opts.spider, error_link)
コード例 #24
0
def test_send_raw_email():
    conn = boto.connect_ses("the_key", "the_secret")

    message = email.mime.multipart.MIMEMultipart()
    message["Subject"] = "Test"
    message["From"] = "*****@*****.**"
    message["To"] = "*****@*****.**"

    # Message body
    part = email.mime.text.MIMEText("test file attached")
    message.attach(part)

    # Attachment
    part = email.mime.text.MIMEText("contents of test file here")
    part.add_header("Content-Disposition", "attachment; filename=test.txt")
    message.attach(part)

    conn.send_raw_email.when.called_with(
        source=message["From"],
        raw_message=message.as_string()).should.throw(BotoServerError)

    conn.verify_email_identity("*****@*****.**")
    conn.send_raw_email(source=message["From"],
                        raw_message=message.as_string())

    send_quota = conn.get_send_quota()
    sent_count = int(send_quota["GetSendQuotaResponse"]["GetSendQuotaResult"]
                     ["SentLast24Hours"])
    sent_count.should.equal(1)
コード例 #25
0
ファイル: alerts.py プロジェクト: Stamped/Stamped
    def sendEmails(self, noop=False):
        logs.info("Submitting emails to %s users" % len(self._emailQueue))

        # Apply rate limit
        limit = 8

        ses = boto.connect_ses(keys.aws.AWS_ACCESS_KEY_ID, keys.aws.AWS_SECRET_KEY)

        for emailAddress, emailQueue in self._emailQueue.iteritems():
            if IS_PROD or emailAddress in self._adminEmails:
                count = 0
                emailQueue.reverse()
                for email in emailQueue:
                    count += 1
                    if count > limit:
                        logs.debug("Limit exceeded for email '%s'" % emailAddress)
                        break

                    try:
                        logs.debug("Send email: %s" % (email))
                        if not noop:
                            ses.send_email(email.sender, email.title, email.body, emailAddress, format='html')

                    except Exception as e:
                        logs.warning("Email failed: %s" % email)
                        logs.warning(utils.getFormattedException())

        logs.info("Success!")
コード例 #26
0
    def setupMailer(self, settings=None):
        self.MailerSettings['FromName']  = settings.get('from_name')
        self.MailerSettings['FromEmail'] = settings.get('from_email')

        print self.MailerSettings
        if not settings.get('aws_ses'):
            self._enable_smtp(settings)
            return

        self.SESHandle = boto.connect_ses(
          aws_access_key_id     = settings.get('aws_ses').get('access_key_id'),
          aws_secret_access_key = settings.get('aws_ses').get('secret_access_key'))

        self.SESSendQuota = self.SESHandle.get_send_quota()["GetSendQuotaResponse"]["GetSendQuotaResult"]
        # Check if we're close to the smtp quota. 10 seems like a good number
        sentLast24Hours = self.SESSendQuota.get('SentLast24Hours')
        if sentLast24Hours is None:
            sentLast24Hours = 0
        sentLast24Hours = int(float(sentLast24Hours))
        max24HourSend = self.SESSendQuota.get('Max24HourSend')
        if max24HourSend is None:
            max24HourSend = 0
        max24HourSend = int(float(max24HourSend))
        if sentLast24Hours >= max24HourSend- 10:
            self._enable_smtp()

        self._enable_aws_ses(settings)
コード例 #27
0
    def setupMailer(self, settings=None):
        self.MailerSettings['FromName'] = settings.get('from_name')
        self.MailerSettings['FromEmail'] = settings.get('from_email')

        print self.MailerSettings
        if not settings.get('aws_ses'):
            self._enable_smtp(settings)
            return

        self.SESHandle = boto.connect_ses(
            aws_access_key_id=settings.get('aws_ses').get('access_key_id'),
            aws_secret_access_key=settings.get('aws_ses').get(
                'secret_access_key'))

        self.SESSendQuota = self.SESHandle.get_send_quota(
        )["GetSendQuotaResponse"]["GetSendQuotaResult"]
        # Check if we're close to the smtp quota. 10 seems like a good number
        sentLast24Hours = self.SESSendQuota.get('SentLast24Hours')
        if sentLast24Hours is None:
            sentLast24Hours = 0
        sentLast24Hours = int(float(sentLast24Hours))
        max24HourSend = self.SESSendQuota.get('Max24HourSend')
        if max24HourSend is None:
            max24HourSend = 0
        max24HourSend = int(float(max24HourSend))
        if sentLast24Hours >= max24HourSend - 10:
            self._enable_smtp()

        self._enable_aws_ses(settings)
コード例 #28
0
ファイル: test_ses.py プロジェクト: DarthLorenzo/moto
def test_delete_identity():
    conn = boto.connect_ses('the_key', 'the_secret')
    conn.verify_email_identity("*****@*****.**")

    conn.list_identities()['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'].should.have.length_of(1)
    conn.delete_identity("*****@*****.**")
    conn.list_identities()['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'].should.have.length_of(0)
コード例 #29
0
    def __init__(self,
                 aws_access_key_id=None,
                 aws_secret_access_key=None,
                 sender=None,
                 reply_to=None,
                 template=None,
                 template_context={},
                 app=None):
        """
        Setup the mail

        """
        if app:
            self.init_app(app)
        else:
            if aws_access_key_id and aws_secret_access_key:
                self.ses = boto.connect_ses(
                    aws_access_key_id=aws_access_key_id,
                    aws_secret_access_key=aws_secret_access_key)

            self.sender = sender
            self.reply_to = reply_to or self.sender

            if template:
                self.template = Template(template=template)
            if template_context:
                self.template_context = template_context
コード例 #30
0
    def send_email(self):
        """
            Function to send email notifications
            """

        content = '<html><body>Hi Team, <br>Canary ' + self.validation_type \
                  + ' validation report for the DAG: ' + self.dag_name \
                  + ' for the execution date ' + self.dag_exec_dt \
                  + '<br><br>Airflow Cluster: ' + self.airflow_cluster_name \
                  + '<br><br><br>' \
                  + '<table width=60% height=40% border=1><tr><td bgcolor=lightgrey>dag_name</td> <td bgcolor="lightgrey">dag_exec_dt</td> <td bgcolor="lightgrey">validation_type</td> <td bgcolor="lightgrey">table_name</td> <td bgcolor="lightgrey">region_cd</td> <td bgcolor="lightgrey">validation_name</td> <td bgcolor="lightgrey">actual_metrics</td> <td bgcolor="lightgrey">expected_metrics</td> <td bgcolor="lightgrey">validation_desc</td> <td bgcolor="lightgrey">validation_status</tr>'

        for (index, result) in self.result_df.iterrows():
            content = content + '<tr><td bgcolor=white>' \
                      + str(result['DAG_NAME']) + '</td> <td bgcolor="white">' \
                      + str(result['DAG_EXEC_DT']) + '</td> <td bgcolor="white">' \
                      + str(result['VALIDATION_TYPE']) \
                      + '</td> <td bgcolor="white">' + str(result['TABLE_NAME']) \
                      + '</td> <td bgcolor="white">' + str(result['REGION_CD']) \
                      + '</td> <td bgcolor="white">' \
                      + str(result['VALIDATION_NAME']) \
                      + '</td> <td bgcolor="white">' + str(result['ACTUAL_METRICS'
                                                           ]) + '</td> <td bgcolor="white">' \
                      + str(result['EXPECTED_METRICS']) \
                      + '</td> <td bgcolor="white">' \
                      + str(result['VALIDATION_DESC'])
            if result['VALIDATION_STATUS'].lower() == 'success':
                content = content + '<td bgcolor="lightgreen">' \
                          + str(result['VALIDATION_STATUS']) + '</tr>'
            elif result['VALIDATION_STATUS'].lower() == 'warning':
                content = content + '<td bgcolor="yellow">' \
                          + str(result['VALIDATION_STATUS']) + '</tr>'
            else:
                content = content + '<td bgcolor="red">' \
                          + str(result['VALIDATION_STATUS']) + '</tr>'

        content += '</td></table></body></html>'

        # Setup subject for the email

        subject = self.env.upper() + ': Canary ' + self.validation_type \
                  + ' Validation ' + self.validation_status + ' for ' \
                  + str(self.dag_name) + ' - ' + str(self.dag_exec_dt)

        # Email configuration

        msg = MIMEMultipart()
        msg['From'] = self.fromaddr
        #msg['To'] = ', '.join(self.toaddr)
        msg['Subject'] = subject
        content = content
        msg.attach(MIMEText(content, 'html'))
        text = msg.as_string()
        # connect to SES
        connection = boto.connect_ses()
        # and send the message
        result = connection.send_raw_email(text,
                                           source=msg['From'],
                                           destinations=self.toaddr)
コード例 #31
0
 def send(self):
     """ Send the email built in the constructor """
     if not SesEmail.is_local:
         # Use aws creds for ses if possible, otherwise, use aws_key from config
         connection = boto.connect_ses()
         try:
             return connection.send_email(self.from_address, self.subject, self.content,
                                          self.to_address, format='html')
         except:
             connection = boto.connect_ses(aws_access_key_id=CONFIG_BROKER['aws_access_key_id'],
                                           aws_secret_access_key=CONFIG_BROKER['aws_secret_access_key'])
             return connection.send_email(self.from_address, self.subject, self.content,
                                          self.to_address, format='html')
     else:
         new_email_text = "\n\n".join(["", "Time", str(datetime.datetime.now()), "Subject", self.subject, "From",
                                      self.from_address, "To", self.to_address, "Content", self.content])
         open(SesEmail.emailLog, "a").write(new_email_text)
コード例 #32
0
ファイル: email.py プロジェクト: aquaya/sawyer
def send_email(recipient, subject, body):
    ''' send an email via SES
    uses the config file's confirmed sender
    '''
    aws = app.config['AWS']
    conn = boto.connect_ses(aws_access_key_id=aws['access_key_id']
            , aws_secret_access_key=aws['secret_access_key'])
    conn.send_email(aws['verified_sender'], subject, body, [recipient])
コード例 #33
0
def cmd_show_quota(args):
    ses = boto.connect_ses()
    args.verbose= True
    
    data = ses.get_send_quota()["GetSendQuotaResponse"]["GetSendQuotaResult"]
    out("Max 24 Hour Send: %s" % data["Max24HourSend"], args)
    out("Sent Last 24 Hours: %s" % data["SentLast24Hours"], args)
    out("Max Send Rate: %s" % data["MaxSendRate"], args)
コード例 #34
0
def test_verify_email_identity():
    conn = boto.connect_ses("the_key", "the_secret")
    conn.verify_email_identity("*****@*****.**")

    identities = conn.list_identities()
    address = identities["ListIdentitiesResponse"]["ListIdentitiesResult"][
        "Identities"][0]
    address.should.equal("*****@*****.**")
コード例 #35
0
def test_delete_identity():
    conn = boto.connect_ses("the_key", "the_secret")
    conn.verify_email_identity("*****@*****.**")

    conn.list_identities()["ListIdentitiesResponse"]["ListIdentitiesResult"][
        "Identities"].should.have.length_of(1)
    conn.delete_identity("*****@*****.**")
    conn.list_identities()["ListIdentitiesResponse"]["ListIdentitiesResult"][
        "Identities"].should.have.length_of(0)
コード例 #36
0
def test_domain_verify():
    conn = boto.connect_ses('the_key', 'the_secret')

    conn.verify_domain_dkim("domain1.com")
    conn.verify_domain_identity("domain2.com")

    identities = conn.list_identities()
    domains = list(identities['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'])
    domains.should.equal(['domain1.com', 'domain2.com'])
コード例 #37
0
def send_report_message(report_target_id):
    try:
        conn = boto.connect_ses()
        subject, message = briefcase.get_report_message(report_target_id)
        conn.send_email(server_email_address, subject, message, server_notification_receiver)
        return True

    except SESError:
        return False
コード例 #38
0
 def email_func(email, auth):
     conn = boto.connect_ses(EMAIL['key'], EMAIL['secret'])
     auth_link = EMAIL['url'] + '?email=%s&auth=%s' % (email, auth)
     return conn.send_email(source=EMAIL['admin'],
                            subject='[%s] - Login Link' % EMAIL['name'],
                            body='<a href="%s">Login</a><br>Email: %s' %
                            (auth_link, email),
                            to_addresses=email,
                            format='html')
コード例 #39
0
ファイル: test_ses.py プロジェクト: DarthLorenzo/moto
def test_domain_verify():
    conn = boto.connect_ses('the_key', 'the_secret')

    conn.verify_domain_dkim("domain1.com")
    conn.verify_domain_identity("domain2.com")

    identities = conn.list_identities()
    domains = list(identities['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'])
    domains.should.equal(['domain1.com', 'domain2.com'])
コード例 #40
0
ファイル: utilities.py プロジェクト: tymiles003/ivrhub
def _send_email(recipient, subject, body):
    ''' send an email using SES from the config's verified sender
    '''
    connection = boto.connect_ses(
        aws_access_key_id=app.config['AWS']['access_key_id'],
        aws_secret_access_key=app.config['AWS']['secret_access_key'])

    result = connection.send_email(app.config['AWS']['verified_sender'],
                                   subject, body, [recipient])
コード例 #41
0
ファイル: groups.py プロジェクト: chbrown/confrm
    def send_email(self, group_id):
        # group = DBSession.query(Group).get(group_id)

        params = self.request.POST
        from_user = DBSession.query(User).get(params['from_user'])
        to_users = DBSession.query(User).filter(User.id.in_(params['to_users']))

        ses_conn = boto.connect_ses()
        ses_conn.send_email(from_user, params['subject'], params['body'], [to_user.full_email for to_user in to_users])
コード例 #42
0
ファイル: __main__.py プロジェクト: Doap/postman
def cmd_send(args):
    ses = boto.connect_ses()
    out("Sending mail to: %s" % ", ".join(args.destinations), args)
    msg = sys.stdin.read()
    r = ses.send_raw_email(msg, args.f, args.destinations)
    if r.get("SendRawEmailResponse", {}).get("SendRawEmailResult", {}).get("MessageId"):
        out("OK", args)
    else:
        out("ERROR: %s" % r, args)
コード例 #43
0
 def sendAWSMail(self, receipients, subject, message, messageFormat='text'):
     logger.info("sending through AWS")
     ses = boto.connect_ses(self._awsKey, self._awsSecret)
     ses.send_email(source=self._email,
                    subject=subject,
                    body=message,
                    to_addresses=receipients,
                    format=messageFormat,
                    reply_addresses=self._email)
コード例 #44
0
ファイル: email.py プロジェクト: jordangumm-progenity/dott
    def send_email(self):
        """
        Sends the email via SES.
        """
        conn = boto.connect_ses(settings.AWS_ACCESS_KEY_ID,
                                settings.AWS_SECRET_ACCESS_KEY)

        conn.send_email(settings.SERVER_EMAIL_FROM, self.subject, self.body,
                        self.to_addresses)
コード例 #45
0
ファイル: users.py プロジェクト: jedahan/picarus
 def email_func(email, api_key, ttl, login_key=None):
     conn = boto.connect_ses(EMAIL['key'], EMAIL['secret'])
     if login_key is None:
         body = '<h2>Email</h2><pre>%s</pre><h2><h2>API Key (Expires in %d seconds)</h2><pre>%s</pre>' % (email, ttl, api_key)
         subject = '[%s] - API Key' % EMAIL['name']
     else:
         body = '<h2>Email</h2><pre>%s</pre><h2>Login Key</h2><pre>%s</pre><h2>API Key (Expires in %d seconds)</h2><pre>%s</pre>' % (email, login_key, ttl, api_key)
         subject = '[%s] - Login/API Key' % EMAIL['name']
     return conn.send_email(source=EMAIL['admin'], subject=subject,
                            body=body, to_addresses=email, format='html')
コード例 #46
0
ファイル: alerter.py プロジェクト: anandhanr/security_monkey
 def mail(self, body, watcher_type):
     ses = boto.connect_ses()
     for email in self.emails:
         try:
             subject = "[{}] Changes in {}".format(self.account, watcher_type)
             ses.send_email(self.from_address, subject, body,  email, format="html")
             app.logger.debug("Emailed {} - {} ".format(email, subject))
         except Exception, e:
             m = "Failed to send failure message: {} {}".format(Exception, e)
             app.logger.debug(m)
コード例 #47
0
    def test_send_mail_ok(self):
        conn = boto.connect_ses('the_key', 'the_secret')
        conn.verify_email_identity(self.sender)

        self.aws_ses_plugin.send_email()

        send_quota = conn.get_send_quota()
        sent_count = int(send_quota['GetSendQuotaResponse']
                         ['GetSendQuotaResult']['SentLast24Hours'])
        self.assertEqual(sent_count, 1)
コード例 #48
0
def test_domain_verify():
    conn = boto.connect_ses("the_key", "the_secret")

    conn.verify_domain_dkim("domain1.com")
    conn.verify_domain_identity("domain2.com")

    identities = conn.list_identities()
    domains = list(identities["ListIdentitiesResponse"]["ListIdentitiesResult"]
                   ["Identities"])
    domains.should.equal(["domain1.com", "domain2.com"])
コード例 #49
0
def sendmail(subject, body):
    try:
        ses = boto.connect_ses(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY)
        ses.send_email('*****@*****.**', str(subject), str(body), '*****@*****.**', format='text')
    except:
        import string, sys, traceback
        exc_type, exc_value, exc_traceback = sys.exc_info()
        
        f = traceback.format_exception(exc_type, exc_value, exc_traceback)
        print string.joinfields(f, '')
コード例 #50
0
def send_email_alert(items):
    ses = boto.connect_ses(settings.AWS_ACCESS_KEY, settings.AWS_SECRET_KEY)
    html_body = jinja_env.get_template('email.html').render(items=items)

    ses.send_email(
        settings.EMAIL_ALERT_FROM,
        'Price drop alert',
        remove_tags(html_body),
        settings.EMAIL_ALERT_TO,
        html_body=html_body
    )
コード例 #51
0
ファイル: email.py プロジェクト: wonderpl/dolly-web
def send_email(recipient, body, subject=None, format='html'):
    if not subject:
        import HTMLParser
        subject = HTMLParser.HTMLParser().unescape(TITLE_RE.search(body).group(1))
    return boto.connect_ses().send_email(
        app.config['DEFAULT_EMAIL_SOURCE'],
        subject,
        body,
        [recipient],
        format=format
    )
コード例 #52
0
def cmd_send(args):
    ses = boto.connect_ses()
    out("Sending mail to: %s" % ", ".join(args.destinations), args)
    msg = sys.stdin.read()
    if args.sanitize:
        msg = sanitize(args, msg)
    r = ses.send_raw_email(msg, args.f, args.destinations)
    if r.get("SendRawEmailResponse", {}).get("SendRawEmailResult", {}).get("MessageId"):
        out("OK", args)
    else:
        out("ERROR: %s" % r, args)
コード例 #53
0
ファイル: utilities.py プロジェクト: aquaya/pipeline
def _send_email(recipient, subject, body):
    ''' send an email using SES from the config's verified sender
    '''
    connection = boto.connect_ses(
        aws_access_key_id=app.config['AWS']['access_key_id']
        , aws_secret_access_key=app.config['AWS']['secret_access_key'])

    result = connection.send_email(
        app.config['AWS']['verified_sender']
        , subject
        , body
        , [recipient])
コード例 #54
0
def test_send_email():
    conn = boto.connect_ses('the_key', 'the_secret')

    conn.send_email.when.called_with("*****@*****.**", "test subject",
        "test body", "*****@*****.**").should.throw(BotoServerError)

    conn.verify_email_identity("*****@*****.**")
    conn.send_email("*****@*****.**", "test subject", "test body", "*****@*****.**")

    send_quota = conn.get_send_quota()
    sent_count = int(send_quota['GetSendQuotaResponse']['GetSendQuotaResult']['SentLast24Hours'])
    sent_count.should.equal(1)
コード例 #55
0
ファイル: default.py プロジェクト: aop/sitsit.fi
def send_mail(subject,msg,address,sender):
	import boto
	conn = boto.connect_ses(
        aws_access_key_id=AWS_ACCESS_KEY,
        aws_secret_access_key=AWS_SECRET_KEY)
	if type(address) != type([]):
		address = [address]
	conn.send_email(
        sender,
        subject,
        msg,
        address)
コード例 #56
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
def get_boto_ses_connection():
    """
    Shortcut for instantiating and returning a boto SESConnection object.

    :rtype: boto.ses.SESConnection
    :returns: A boto SESConnection object, from which email sending is done.
    """

    access_key_id = getattr(settings, "CUCUMBER_SES_ACCESS_KEY_ID", getattr(settings, "AWS_ACCESS_KEY_ID", None))
    access_key = getattr(settings, "CUCUMBER_SES_SECRET_ACCESS_KEY", getattr(settings, "AWS_SECRET_ACCESS_KEY", None))

    return boto.connect_ses(aws_access_key_id=access_key_id, aws_secret_access_key=access_key)
コード例 #57
0
ファイル: jobsmgr.py プロジェクト: Katafalkas/mongo-perf
    def send_reports(self, definition):
        """Sends reports based on generated report
        """
        current_date = self.date.strftime("%Y-%m-%d")
        from boto import connect_ses

        if definition.report:
            header = REPORT_INFO_HEADER.substitute({"date": current_date, "name": definition.name})
            message = header + definition.report
            connect_ses().send_email(
                "mongo-perf admin <*****@*****.**>",
                "MongoDB Performance Report",
                message,
                definition.recipients,
                format="html",
            )
        else:
            if definition.no_data:
                connect_ses().send_email(
                    "mongo-perf admin <*****@*****.**>",
                    "MongoDB Performance Report",
                    NO_DATA_INFO,
                    definition.recipients,
                    format="html",
                )
            else:
                message = NO_REPORT_INFO_HEADER.substitute({"date": current_date, "name": definition.name})
                connect_ses().send_email(
                    "mongo-perf admin <*****@*****.**>",
                    "MongoDB Performance Report",
                    message,
                    definition.recipients,
                    format="html",
                )