class SESConnectionTest(unittest.TestCase): ses = True def setUp(self): self.ses = SESConnection() def test_get_dkim_attributes(self): response = self.ses.get_identity_dkim_attributes(['example.com']) # Verify we get the structure we expect, we don't care about the # values. self.assertTrue('GetIdentityDkimAttributesResponse' in response) self.assertTrue('GetIdentityDkimAttributesResult' in response['GetIdentityDkimAttributesResponse']) self.assertTrue( 'DkimAttributes' in response['GetIdentityDkimAttributesResponse']\ ['GetIdentityDkimAttributesResult']) def test_set_identity_dkim_enabled(self): # This api call should fail because have not verified the domain, # so we can test that it at least fails we we expect. with self.assertRaises(exceptions.SESIdentityNotVerifiedError): self.ses.set_identity_dkim_enabled('example.com', True) def test_verify_domain_dkim(self): # This api call should fail because have not confirmed the domain, # so we can test that it at least fails we we expect. with self.assertRaises(exceptions.SESDomainNotConfirmedError): self.ses.verify_domain_dkim('example.com')
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'])
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)
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)
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 # 送信先のアドレスリスト )
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)
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
class AmazonSEService(EmailService): def __init__(self, *args, **kwargs): """ Initializes the Amazon SES email service. """ self.connection = None self.id = settings.EMAIL_SERVICES_CLIENT_ID self.key = settings.EMAIL_SERVICES_CLIENT_KEY 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) def close(self): """ Creates the connection that will interact with the Amazon API using Boto. """ if not self.connection: return self.connection.close() self.connection = None def send_messages(self, email_messages): """ Sends one or more email messages using throught amazon SES using boto. """ if not self.connection: self.open() for message in email_messages: self.connection.send_raw_email( source=message.from_email, destinations=message.recipients(), raw_message=message.message().as_string())
class AmazonSESMailer(BaseMailer): """A mailer for Amazon Simple Email Server. Requires the `boto` python library. """ def __init__(self, aws_access_key_id, aws_secret_access_key, return_path=None, *args, **kwargs): """ """ from boto.ses.connection import SESConnection self.conn = SESConnection( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key ) assert self.conn self.return_path = return_path super(AmazonSESMailer, self).__init__(*args, **kwargs) def send_messages(self, *email_messages): """ """ logger = logging.getLogger('mailshake:AmazonSESMailer') if not email_messages: logger.debug('No email messages to send') return for msg in email_messages: data = { 'source': msg.from_email, 'subject': msg.subject, 'body': msg.html or msg.text, 'to_addresses': msg.to, 'cc_addresses': msg.cc or None, 'bcc_addresses': msg.bcc or None, 'reply_addresses': msg.reply_to or None, 'format': 'html' if msg.html else 'text', } if self.return_path: data['return_path'] = self.return_path logger.debug('Sending email from {0} to {1}'.format(msg.from_email, msg.to)) self.conn.send_email(**data)
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
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()
def __init__(self, aws_access_key_id, aws_secret_access_key, return_path=None, *args, **kwargs): """ """ from boto.ses.connection import SESConnection self.conn = SESConnection( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key ) assert self.conn self.return_path = return_path super(AmazonSESMailer, self).__init__(*args, **kwargs)
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
class EmailProcessor(object): def __init__(self): self.con = SESConnection() def send_success(self, to, id): msg = """Hello! This is an automated email from Sentimentron. Sentimentron's finished processing your request and has produced some results. To view them, copy the following into your browser: <ul style="list-style-type:none"><li><a href="http://results.sentimentron.co.uk/index.html#%d">http://results.sentimentron.co.uk/index.html#%d</a></li></ul> Hope you find the results useful! If you have any questions or feedback, please email <a href="mailto:[email protected]">[email protected]</a>.""" % (id, id) self.con.send_email("*****@*****.**", "Good news from Sentimentron", msg + FOOTER, [to], None, None, 'html' ) def send_failure(self, to, error): msg = """Hello! This is an automated email from Sentimentron. Unfortunately, Sentimentron encountered a problem processing your query and hasn't produced any results. Apologies for the inconvenience. The problem was: <ul style="list-style-type:none; font-weight:bold"><li>%s</li></ul> If you have any questions or feedback, please email <a href="mailto:[email protected]">[email protected]</a>.""" % (error,) self.con.send_email('*****@*****.**', 'Bad news from Sentimentron', msg + FOOTER, [to], None, None, 'html' )
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)
def send(self): connection = SESConnection(self.app.config['AWS_ACCESS_KEY'], self.app.config['AWS_SECRET']) connection.send_email(self.sender, self.subject, self.body, self.recipient)
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)
def SendEmail(to,subject,message,from_addr="*****@*****.**",format="html"): conn = SESConnection(AWS_ACCESS_KEY,AWS_SECRET_ACCESS_KEY) conn.send_email(from_addr,subject,message,to,format=format)
def setUp(self): self.ses = SESConnection()
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)
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)
#! /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@'])
class SESConnectionTest (unittest.TestCase): def get_suite_description(self): return 'SES connection test suite' def setUp(self): self.conn = SESConnection() self.test_email = '*****@*****.**' def test_1_connection(self): """ Tests insantiating basic connection """ c = SESConnection() assert c def test_2_get_send_statistics(self): """ Tests retrieving send statistics """ assert self.conn.get_send_statistics() def test_3_get_send_quota(self): """ Tests retrieving send quota """ assert self.conn.get_send_quota() def test_4_get_verified_emails(self): """ Tests retrieving list of verified emails """ assert self.conn.get_verified_emails() def test_5_verify_email_address(self): """ Tests verifying email address """ assert self.conn.verify_email_address(email=self.test_email) def test_6_send_email(self): """ Tests sending an email """ assert self.conn.send_email(source=self.test_email, subject='Test', message='Test Message', to='self.test_email') # Email with cc and bcc assert self.conn.send_email(source=self.test_email, subject='Test', message='Test Message', to=[self.test_email], cc=[self.test_email], bcc=[self.test_email]) def test_7_send_raw_email(self): """ Tests sending a raw email """ assert self.conn.send_raw_email(source=self.test_email, message=self._create_raw_email_message()) def test_8_delete_verified_email(self): """ Tests deleting verified email """ assert self.conn.delete_verified_email(email=self.test_email) def _create_raw_email_message(self): """ Creates a test mime-type email using native Email class """ me = self.test_email you = self.test_email # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['From'] = me msg['To'] = you msg['Subject'] = "Link" # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) return msg
def __init__(self): self.con = SESConnection()
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)
# -*- 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),
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"]
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)
def setUp(self): self.conn = SESConnection() self.test_email = '*****@*****.**'
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"]