def __init__(self, api_key): import sendwithus import sendwithus.encoder class JSONEncoder(sendwithus.encoder.SendwithusJSONEncoder): def default(self, obj): import bson import datetime if isinstance(obj, datetime.datetime): return { 'year': obj.year, 'month': obj.month, 'day': obj.day, 'hour': obj.hour, 'minute': obj.minute, 'second': obj.second, 'weekday': obj.weekday(), } if isinstance(obj, bson.ObjectId): return str(obj) return super().default(obj) self.__json_encoder = JSONEncoder self.__swu = sendwithus.api(api_key=api_key, json_encoder=self.__json_encoder) self.__load_templates()
def test_invalid_request(api_key, api_options): """Test raises APIError with invalid api request & raise_errors=True""" swu_api = sendwithus.api(api_key, raise_errors=True, **api_options) with pytest.raises(APIError): swu_api.create_email('name', '', '<html><head></head><body></body></html>')
def test_raise_errors_option(api_key, api_options): """Test raises no exception if raise_errors=False""" swu_api = sendwithus.api(api_key, raise_errors=False, **api_options) response = swu_api.create_email('name', '', '<html><head></head><body></body></html>') assert 400 == response.status_code
def main(): global swu parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument('-a', '--apikey', type=str, required=True) parser.add_argument('command', choices=CMD_COMMANDS) parser.add_argument('resource', choices=CMD_RESOURCES) parser.add_argument('directory', nargs='?', default='.') args = parser.parse_args() swu = sendwithus.api(args.apikey) func_map = { 'pull': { 'snippets': pull_snippets, 'templates': pull_templates }, 'push': { 'snippets': push_snippets, 'templates': push_templates } } try: func = func_map[args.command][args.resource] except KeyError: print 'Unknown Command: {} {}'.format(args.command, args.resource) else: func(swu, args.directory)
def setUp(self): self.api = api(self.API_KEY, **self.options) self.email_address = '*****@*****.**' self.segment_id = 'seg_VC8FDxDno9X64iUPDFSd76' self.recipient = { 'name': 'Matt', 'address': '*****@*****.**'} self.incomplete_recipient = {'name': 'Matt'} self.email_data = { 'name': 'Jimmy', 'plants': ['Tree', 'Bush', 'Shrub']} self.email_data_with_decimal = { 'decimal': decimal.Decimal('5.5') } self.sender = { 'name': 'Company', 'address': '*****@*****.**', 'reply_to': '*****@*****.**'} self.cc_test = [{ 'name': 'Matt CC', 'address': '*****@*****.**'}] self.bcc_test = [{ 'name': 'Matt BCC', 'address': '*****@*****.**'}] self.enabled_drip_campaign_id = 'dc_Rmd7y5oUJ3tn86sPJ8ESCk' self.disabled_drip_campaign_id = 'dc_AjR6Ue9PHPFYmEu2gd8x5V' self.false_drip_campaign_id = 'false_drip_campaign_id'
def send_with_template(reciever,data,subject,sender): #subject is optional import sendwithus api = sendwithus.api(api_key='sendwithus API key') r = api.send( email_id='template ID', recipient= {# give the reciever here 'address': reciever }, email_data={#you can change the tags and variables here 'company_name':'DSC VIT', 'name': data['name'], 'reg_no':data['regno'] }, locale='en-IN' #specify the location #you can also add sender details if required '''sender={ 'address': sender, 'reply_to':'*****@*****.**', # Optional 'name': 'Company' # Optional }''' #esp_account='Your esp ID' #you can also add this param if you want to use email delivering service ) print (r.status_code) #response code
def send_welcome_email(email_address): api_key = os.environ['SEND_WITH_US'] set_password_link = create_link(email_address, 'password') swu = sendwithus.api(api_key) swu.send( email_id='tem_58MQPDcuQvGKoXG3aVp4Zb', recipient={'address': email_address}, email_data={'setPasswordLink': set_password_link})
def send_testmail(self, data): api = sendwithus.api(api_key=settings.SWU_API_KEY) r = api.send( email_id='tem_ed8qjPxQtAEqHwDWVzNwU4', recipient={'address': '*****@*****.**'}, email_data=data ) return r
def test_authentication_error(api_options): """Test raises AuthenticationError with invalid api key""" invalid_api = sendwithus.api('INVALID_KEY', raise_errors=True, **api_options) with pytest.raises(AuthenticationError): invalid_api.emails()
def send_password_reset_email(email_address): api_key = os.environ['SEND_WITH_US'] set_password_link = create_link(email_address, 'password') swu = sendwithus.api(api_key) swu.send( email_id='tem_shSnhmqCSMAwdLbPhuwY4U', recipient={'address': email_address}, email_data={'setPasswordLink': set_password_link})
def test_send_invalid_apikey(self): """ Test send with invalid API key. """ invalid_api = api('INVALID_API_KEY', **self.options) result = invalid_api.send( self.EMAIL_ID, self.recipient, email_data=self.email_data) self.assertFail(result) self.assertEqual(result.status_code, 403) # bad api key
def test_authentication_error(api_options): """Test raises AuthenticationError with invalid api key""" invalid_api = sendwithus.api( 'INVALID_KEY', raise_errors=True, **api_options ) with pytest.raises(AuthenticationError): invalid_api.emails()
def test_invalid_request(self): """Test raises APIError with invalid api request & raise_errors=True""" swu_api = api(self.API_KEY, raise_errors=True, **self.options) self.assertRaises( APIError, swu_api.create_email, 'name', '', '<html><head></head><body></body></html>' )
def save(self): api = sendwithus.api(api_key=settings.SWU_API_KEY) template_id = self.cleaned_data['email_templates'] for d in self.get_data(self.cleaned_data): res = api.send( email_id=template_id, recipient={'address': d['email']}, email_data=d ) if res.status_code != 200: raise Exception(res.text) break
def setUp(self): self.api = api(self.API_KEY, **self.options) self.recipient = { 'name': 'Matt', 'address': '*****@*****.**'} self.incomplete_recipient = {'name': 'Matt'} self.email_data = { 'name': 'Jimmy', 'plants': ['Tree', 'Bush', 'Shrub']} self.sender = { 'name': 'Company', 'address':'*****@*****.**', 'reply_to':'*****@*****.**'}
def test_invalid_request(api_key, api_options): """Test raises APIError with invalid api request & raise_errors=True""" swu_api = sendwithus.api( api_key, raise_errors=True, **api_options ) with pytest.raises(APIError): swu_api.create_email( 'name', '', '<html><head></head><body></body></html>' )
def test_send_invalid_apikey( api_options, email_id, recipient, email_data ): """ Test send with invalid API key. """ invalid_api = sendwithus.api('INVALID_API_KEY', **api_options) result = invalid_api.send( email_id, recipient, email_data=email_data ) assert result.status_code == 403 # bad api key
def test_raise_errors_option(api_key, api_options): """Test raises no exception if raise_errors=False""" swu_api = sendwithus.api( api_key, raise_errors=False, **api_options ) response = swu_api.create_email( 'name', '', '<html><head></head><body></body></html>' ) assert 400 == response.status_code
def main(): main_parser = argparse.ArgumentParser(description=DESCRIPTION) main_parser.add_argument('-a', '--apikey', type=str, required=True, help="required, used for authentication") main_parser.add_argument('-d', '--data', type=str, required=False, help="optional, required only in conjunction with render command, specifies a file containing data used for template rendering") main_parser.add_argument('-e', '--email', type=str, required=False, help="optional, required only in conjunction with send command, specifies the email address to which the email will be sent to") subparsers = main_parser.add_subparsers(help='commands', dest='command') pull_parser = subparsers.add_parser('pull', help='process pull templates and snippets') pull_parser.add_argument('resource', choices=CMD_RESOURCES) pull_parser.add_argument('directory', nargs='?', default='.') push_parser = subparsers.add_parser('push', help='process push templates and snippets') push_parser.add_argument('resource', choices=CMD_RESOURCES) push_parser.add_argument('directory', nargs='?', default='.') render_parser = subparsers.add_parser('render', help='process render templates') render_parser.add_argument('template', nargs='?', help="Required, specifies path to template version which is to be rendered. <template_name>/<template_version>.html") send_parser = subparsers.add_parser('send', help='process send email') send_parser.add_argument('template', nargs='?', help="Required, specifies path to template version which is to be sent. <template_name>/<template_version>.html") args = main_parser.parse_args() swu = sendwithus.api(args.apikey) func_map = { 'pull': { 'snippets': pull_snippets, 'templates': pull_templates }, 'push': { 'snippets': push_snippets, 'templates': push_templates } } try: if args.command == 'render': render_template(swu, args.data, args.template) elif args.command == 'send': send_mail(swu, args.data, args.email, args.template) else: func = func_map[args.command][args.resource] func(swu, args.directory) except KeyError: print 'Unknown Command: {} {}'.format(args.command, args.resource)
def get_swu_templates(): key = settings.SWU_API_KEY api = sendwithus.api(api_key=key) resp = api.emails() return resp.json()
def test_raise_errors_option(self): """Test raises no exception if raise_errors=False""" swu_api = api(self.API_KEY, raise_errors=False, **self.options) response = swu_api.create_email('name', '', '<html><head></head><body></body></html>') self.assertEqual(400, response.status_code)
def setUp(self): self.api = api(self.API_KEY, **self.options)
import json from flask import Flask, jsonify, request, render_template import sendwithus api = sendwithus.api(api_key='test_a1352c77daceca6ad24ba21a28b071735ee53f73') with open('templates/share_photos.html') as f: res = api.create_template( name='Email Name', subject='Email Subject', html=f.read(), text='Optional text content' ) share_template_id = res.json()['id'] app = Flask(__name__) with open('photos.json') as f: photos = json.loads(f.read()) @app.route('/') def index(): return render_template('index.html') def gen_photos(q): for photo in photos: if q in photo['title']: yield photo
def __init__(self, app): api_key = app.config["SENDWITHUS_API_KEY"] self.api = sendwithus.api(api_key=api_key)
def api(api_key, api_options): return sendwithus.api(api_key, **api_options)
def api(self): ctx = _app_ctx_stack.top if not hasattr(ctx, 'sendwithus_api'): ctx.sendwithus_api = sendwithus_api.api(api_key=self.api_key, **self.api_options) return ctx.sendwithus_api
from __future__ import absolute_import # django/libs import sendwithus from django.conf import settings api = sendwithus.api(api_key=settings.SENDWITHUS_KEY)
def __init__(self): self.api = sendwithus.api(api_key=settings.SENDWITHUS_KEY)
def test_authentication_error(self): """Test raises AuthenticationError with invalid api key""" invalid_api = api('INVALID_KEY', raise_errors=True, **self.options) self.assertRaises(AuthenticationError, invalid_api.emails)