Exemplo n.º 1
0
def send_emails(args, config):
    template = config.get('template', 'default')
    if template not in EMAIL_TEMPLATES:
        log.error(
            'No handler for mail template "%s" found, skip sending emails',
            template)
        return

    if 'emails' not in config:
        log.error('No emails found in config, skip sending emails')
        return

    handler = EMAIL_TEMPLATES[template]
    msg = handler(args, config)
    msg['From'] = '*****@*****.**'
    msg['To'] = ','.join(config['emails'])
    if 'subject' in config:
        msg['Subject'] = config['subject']
    else:
        msg['Subject'] = 'Test results for %s (%s)' % (args.timestamp,
                                                       config['name'])

    conn = SESConnection(
        #credentials!
    )
    conn.send_raw_email(msg.as_string())
    log.debug('Sent "%s" mail for test %s to %s', template, config['name'],
              config['emails'])
Exemplo n.º 2
0
def get_ses_connection(args):
    """Given a set of parsed arguments, returns an SESConnection."""
    credentials = parse_aws_credentials_file(args.credentials_file)
    region = RegionInfo(endpoint=args.host)
    connection = SESConnection(debug=(2 if args.verbose else 0), **credentials)
    region.connection = connection
    return connection
Exemplo n.º 3
0
    def open(self):
        """
        Creates the connection that will interact with the Amazon API
        using Boto.
        """
        if self.connection:
            return

        self.connection = SESConnection(aws_access_key_id=self.id,
                                        aws_secret_access_key=self.key)
Exemplo n.º 4
0
def get_ses_quota():
    '''
    Returns the simple Amazon SES quota info, in text.
    '''
    # Open the connection. Uses creds from boto conf or env vars.
    conn = SESConnection()

    quota = conn.get_send_quota()

    conn.close()

    return json.dumps(quota, indent=2)
Exemplo n.º 5
0
def send_mail(mail_address, mail_title, mail_text):
    conn = SESConnection()
    to_addresses = [mail_address]
    # SendMail APIを呼び出す
    conn.send_email(
        '*****@*****.**'  # 送信元アドレス
        ,
        mail_title  # メールの件名
        ,
        mail_text  # メールの本文
        ,
        to_addresses  # 送信先のアドレスリスト 
    )
Exemplo n.º 6
0
def get_ses_quota():
    '''
    Returns the simple Amazon SES quota info, in text.
    '''
    # Open the connection. Uses creds from boto conf or env vars.
    conn = SESConnection()

    quota = conn.get_send_quota()

    # Getting an error when we try to call this. See:
    # http://code.google.com/p/boto/issues/detail?id=518
    #conn.close()

    return json.dumps(quota, indent=2)
def test_send_emails(vars):
    aws_key = 'YOUR_AWS_KEY'
    aws_secret_key = 'YOUR_SECRET_KEY'
    from boto.ses.connection import SESConnection
    conn = SESConnection(aws_key, aws_secret_key)
    return conn.send_email(source=vars.source,
                           subject=vars.subject, 
                           body=vars.body,
                           to_addresses=vars.to_addresses,
                           cc_addresses=vars.cc_addresses,
                           bcc_addresses=vars.bcc_addresses,
                           format=vars.format,
                           reply_addresses=vars.reply_addresses,
                           return_path=vars.return_path)
Exemplo n.º 8
0
def get_ses_send_stats():
    """
    Fetches the Amazon SES, which includes info about bounces and complaints.
    Processes that data, returns some text suitable for the email.
    """

    # Open the connection. Uses creds from boto conf or env vars.
    conn = SESConnection()

    stats = conn.get_send_statistics()

    conn.close()

    one_day_ago = datetime.datetime.now() - datetime.timedelta(1)
    one_week_ago = datetime.datetime.now() - datetime.timedelta(7)

    one_day_ago_counter = collections.Counter()
    one_week_ago_counter = collections.Counter()
    two_weeks_ago_counter = collections.Counter()

    for dp in stats['GetSendStatisticsResponse']['GetSendStatisticsResult']['SendDataPoints']:
        dt = datetime.datetime.strptime(str(dp['Timestamp']).translate(None, ':-'), "%Y%m%dT%H%M%SZ")

        dp_count = {k: int(v) for k, v in dp.items() if v.isdigit()}

        if dt > one_day_ago:
            one_day_ago_counter.update(dp_count)

        if dt > one_week_ago:
            one_week_ago_counter.update(dp_count)
        else:
            two_weeks_ago_counter.update(dp_count)

    res = 'SES Send Stats\n====================================='
    for title, data in (('Last Day', one_day_ago_counter), ('Last Week', one_week_ago_counter), ('Two Weeks Ago', two_weeks_ago_counter)):
        res += '\n%s\n---------------------------------' % (title)
        for i, k in enumerate(('DeliveryAttempts', 'Bounces', 'Complaints', 'Rejects')):
            res += '\n%16s: %5s' % (k, data[k])
            if i != 0:
                res += ' (%d%%)' % (100 * data[k] / data['DeliveryAttempts'])

    return res
Exemplo n.º 9
0
    def process_message(self, peer, mailfrom, rcpttos, data):
        # Print the request information
        sys.stdout.write(u"Receiving message from: %s\n" % str(peer))
        sys.stdout.write(u"Message addressed from: %s\n" % str(mailfrom))
        sys.stdout.write(u"Message addressed to: %s\n" % str(rcpttos))
        sys.stdout.write(u"Message length: %s\n" % str(len(data)))
        sys.stdout.flush()

        # Parse the message and remove headers that are offensive to SES
        msg = Parser().parsestr(data)
        if 'Errors-To' in msg:
            del msg['Errors-To']

        # Send out via SES
        try:
            connection = SESConnection(aws_access_key_id=self.aws_key,
                                       aws_secret_access_key=self.aws_secret)
            connection.send_raw_email(msg.as_string(), source=mailfrom)
        except BotoServerError, err:
            sys.stderr.write(str(err))
            sys.stdout.flush()
Exemplo n.º 10
0
def send_raw_email_amazonses(raw_email,
                             from_address,
                             recipient=None,
                             aws_key=None,
                             aws_secret_key=None):
    '''
    Send the raw email via Amazon SES.
    If the credential arguments are None, boto will attempt to retrieve the
    values from environment variables and config files.
    recipient seems to be redudant with the values in the raw email headers.
    '''

    conn = SESConnection(aws_key, aws_secret_key)

    if isinstance(recipient, str) or isinstance(recipient, unicode):
        recipient = [recipient]

    conn.send_raw_email(raw_email, source=from_address, destinations=recipient)

    # Getting an error when we try to call this. See:
    # http://code.google.com/p/boto/issues/detail?id=518
    #conn.close()

    return True
Exemplo n.º 11
0
 def test_ses_expiration(self):
     c = SESConnection(aws_access_key_id='aws_access_key_id',
                       aws_secret_access_key='aws_secret_access_key')
     self.assert_is_expired(c, SES_EXPIRED, status=403)
     self.assert_is_not_expired(c, GENERIC_BAD_REQUEST, status=403)
Exemplo n.º 12
0
 def setUp(self):
     self.ses = SESConnection()
Exemplo n.º 13
0
def send_email(subject, body):
    connection = SESConnection(aws_access_key_id=AWS_ACCESS_KEY_ID,
                               aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

    connection.send_email(FROM_EMAIL, subject, body, TO_EMAIL)
Exemplo n.º 14
0
	def emit(self,record):
		conn = SESConnection(AWS_ACCESS_KEY,AWS_SECRET_ACCESS_KEY)
		conn.send_email(self.fromaddr,self.subject,self.format(record),self.toaddrs)
Exemplo n.º 15
0
# -*- coding: utf-8 -*-

from jinja2 import Environment, FileSystemLoader
from boto.ses.connection import SESConnection
from config import AWSID, AWSKEY, TEMPLATE
from email.header import Header

conn = SESConnection(AWSID, AWSKEY)
env = Environment(loader=FileSystemLoader(TEMPLATE))

COSCUP_TEAM_ADMIN = u'COSCUP 行政組'
COSCUP_TEAM_ADMIN_MAIL = u'*****@*****.**'


def mail_header(name, mail):
    ''' Encode header to base64
    :param str name: user name
    :param str mail: user mail
    :rtype: string
    :returns: a string of "name <mail>" in base64.
    '''
    return '"%s" <%s>' % (Header(name, 'utf-8'), mail)


def send_first(info):

    try:
        template = env.get_template('coscup_first.html')

        r = conn.send_email(
            source=mail_header(COSCUP_TEAM_ADMIN, COSCUP_TEAM_ADMIN_MAIL),
Exemplo n.º 16
0
#! /usr/bin/env python
from boto.ses.connection import SESConnection
import os
import sys
import subprocess
import socket

TMPFILE = '/var/run/postgresql/last-wal-archive-error-file.tmp'

if __name__ == '__main__':
    return_code = 'unknown'
    host = socket.getfqdn()
    wal_file = 'unknown'
    try:
        ses_conn = SESConnection()
        wal_file = sys.argv[1]
        wal_push = '/usr/local/bin/wal-e'
        return_code = subprocess.call([wal_push, 'wal-push', wal_file])
    except Exception, e:
        return_code = str(e)
    finally:
        if return_code != 0:
            if os.path.exists(TMPFILE):
                contents = open(TMPFILE).read()
                last_wal_error = contents
                if wal_file == last_wal_error:
                    ses_conn.send_email(source='youremail@',
                                        subject='PG WAL Archive Failed!',
                                        body='Host: %s\nError: %s\nWAL: %s' %
                                        (host, return_code, wal_file),
                                        to_addresses=['toemail@'])
Exemplo n.º 17
0
 def emit(self, record):
     conn = SESConnection(self.aws_access_key_id,
                          self.aws_secret_access_key)
     conn.send_email(self.fromaddr, self.subject, self.format(record),
                     self.toaddrs)
Exemplo n.º 18
0
def send(fromAddr, rcptTo, data):
    conn = SESConnection(aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
                         aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
    conn.send_raw_email(data, destinations=rcptTo)
Exemplo n.º 19
0
 def test_ses_expiration(self):
     c = SESConnection()
     self.assert_is_expired(c, SES_EXPIRED, status=403)
     self.assert_is_not_expired(c, GENERIC_BAD_REQUEST, status=403)
Exemplo n.º 20
0
import os, pwd, grp

f = open('/tmp/.uwsgi.lock', 'w+')
f.close()
uid = pwd.getpwnam('oskar').pw_uid
gid = grp.getgrnam('oskar').gr_gid
os.chown('/tmp/.uwsgi.lock', uid, gid)

import ctypes
from ctypes import CDLL

pylibc = CDLL("/home/ella/Ella/ella/awsenckeys.so")
pylibc.awsakey.restype = ctypes.c_char_p
pylibc.awsskey.restype = ctypes.c_char_p

AWSAKEY = pylibc.awsakey()
AWSSKEY = pylibc.awsskey()

######################################################

conn = SESConnection(AWSAKEY, AWSSKEY)
data = conn.get_send_statistics()
data = data["GetSendStatisticsResponse"]["GetSendStatisticsResult"]
for i in data["SendDataPoints"]:
    print "Complaints: %s" % i["Complaints"]
    print "Timestamp: %s" % i["Timestamp"]
    print "DeliveryAttempts: %s" % i["DeliveryAttempts"]
    print "Bounces: %s" % i["Bounces"]
    print "Rejects: %s" % i["Rejects"]