Package: sendwithus
sendwithus python-clientRequirementsPython requests libraryInstallationpip install sendwithusUsageFor all examples, assume:importsendwithusapi=sendwithus.api(api_key='YOUR-API-KEY')Error HandlingBy default, the API calls return a response object. However, you can usesendwithus.api(api_key='YOUR-API-KEY', raise_errors=True)which will raise the following errors:AuthenticationError- Caused by an invalid API keyAPIError- Caused by an invalid API request (4xx error)ServerError- Caused by a server error (5xx error)Errors can be imported from thesendwithus.exceptionsmodule.TemplatesGet Your Templatesapi.templates()Get a Specific Templateapi.get_template('YOUR-TEMPLATE-ID')Get a Specific Template Versionapi.get_template('YOUR-TEMPLATE-ID',version='YOUR-VERSION-ID')Create a Templateapi.create_template(name='Email Name',subject='Email Subject',html='<html><head></head><body>Valid HTML</body></html>',text='Optional text content',preheader='Optional preheader')Create a New Localeapi.create_new_locale('YOUR-TEMPLATE-ID',locale='fr-FR',version_name='Version Name',subject='Email Subject',html='<html><head></head><body>Valid HTML</body></html>',text='Optional text content',preheader='Optional preheader')Create a New Versionapi.create_new_version(template_id='YOUR-TEMPLATE-ID',name='Version Name',subject='Email Subject',html='<html><head></head><body>Valid HTML</body></html>',text='Optional text content',preheader='Optional preheader',locale='fr-FR')Update a Template Versionapi.update_template_version(template_id='YOUR-TEMPLATE-ID',version_id='YOUR-VERSION-ID',name='Email Name'subject='Email Subject',html='<html><head></head><body>Valid HTML</body></html>',text='Optional text content',preheader='Optional preheader')We validate all HTML and will return an error if it's invalid.r.status_code# 400r.content# 'email html failed to validate'SendNOTE- If a customer does not exist by the specified email (recipient address), the send call will create a customer.email_id                      — Template ID to sendrecipientaddress                    — The recipient's email addressname (optional)            — The recipient's nameemail_data (optional)         — Object containing email template datasender (optional)address                    — The sender's email addressreply_to                   — The sender's reply-to addressname                       — The sender's namecc (optional)                 — A list of CC recipients, of the format {'address': 'cc@email.com'}bcc (optional)                — A list of BCC recipients, of the format {'address': 'bcc@email.com'}headers (options)             — Object contain SMTP headers to be included with the emailesp_account (optional)       — ID of the ESP Account to send this email through. ex: esp_1a2b3c4d5efiles (optional)              — List of file attachments (combined maximum 7MB)inline (optional)             — Inline attachment objectlocale (optional)             — Template locale to send (ie: en-US)email_version_name (option)   — Template version to send (ie: Version A)Call with REQUIRED parameters onlyTheemail_datafield is optional, but highly recommended!r=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'address':'us@sendwithus.com'})printr.status_code# 200Call with REQUIRED parameters and email_datar=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'address':'us@sendwithus.com'},email_data={'first_name':'Matt'})printr.status_code# 200Optional SenderThesender['address']is a required sender field.sender['name']andsender['reply_to']are both optional.r=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},email_data={'first_name':'Matt'},sender={'address':'company@company.com','reply_to':'info@company.com',# Optional'name':'Company'# Optional})printr.status_code# 200Optional CCr=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},cc=[{'address':'company@company.com'},{'address':'info@company.com'}])printr.status_code# 200Optional BCCr=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},bcc=[{'address':'company@company.com'},{'address':'info@company.com'}])printr.status_code# 200Optional Headersr=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},headers={'X-HEADER-ONE':'header-value'})printr.status_code# 200Optional ESP Accountr=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},esp_account='YOUR-ESP-ID')printr.status_code# 200Optional File Attachmentsr=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},files=[open('/home/Matt/report1.txt','r'),open('/home/Matt/report2.txt','r')])printr.status_code# 200Optional File Attachments with explicit file namesr=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},files=[{'file':open('/home/Matt/report1.txt','r'),'filename':'arbitrary_file_name.xyz'}])printr.status_code# 200Optional Inline Imager=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},inline=open('image.jpg','r'))printr.status_code# 200Optional Inline Image with explicit file namesr=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},inline={'file':open('/home/Matt/image.jpg','r'),'filename':'cool_image.jpg'})printr.status_code# 200Optional Localer=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},locale='fr-FR')printr.status_code# 200Optional Version Namer=api.send(email_id='YOUR-TEMPLATE-ID',recipient={'name':'Matt','address':'us@sendwithus.com'},email_version_name='Version A')printr.status_code# 200Drip CampaignsList all Drip CampaignsList all drip campaigns for the current profileapi.list_drip_campaigns()Start a Customer on a Drip CampaignStarts a customer on the first step of a specified drip campaignapi.start_on_drip_campaign('dc_1234asdf1234',{'address':'customer@email.com'})Start a Customer on a Drip Campaign with email_dataYou may specify extra data to be merged into the templates in the drip campaign.Note&emdash; Any data provided in theemail_dataparameter forstart_on_drip_campaign()will be used throughout the entire drip campaign.api.start_on_drip_campaign('dc_1234asdf1234',{'address':'customer@email.com'},email_data={'color':'blue'},sender={'address':'from@email.com'},cc=[{'address':'cc@email.com'}],tags=['tag_one','tag_two'],esp_account='esp_1234',locale='fr-FR')Remove a Customer from a Drip CampaignDeactivates all pending emails for a customer on a specified drip campaignapi.remove_from_drip_campaign('customer@email.com','dc_1234asdf1234')Remove a Customer from all Drip CampaignsYou can deactivate all pending drip campaign emails for a customerapi.drip_deactivate('customer@example.com')Remove a Customer from a Single Drip Campaignsapi.remove_from_drip_campaign('customer@example.com','dc_1234asdf1234')List the details of a specific Drip Campaignapi.drip_campaign_details('dc_1234asdf1234')CustomersGet a Customerapi.customer_details('customer@example.com')Create/Update Customer LocaleYou can use the same endpoint to create or update a customer. This is primarily
used to associate a locale with an email address so Sendwithus can
automatically send them the correct template. Note that if your templates are
only in one language then you don't need to use this feature.api.customer_create('customer@example.com',locale="fr-FR")Delete a Customerapi.customer_delete('customer@example.com')SnippetsGet All Snippetsapi.snippets()Get a Specific Snippetapi.get_snippet('snp_1234asdf1234')Create a Snippetapi.create_snippet(name='My Snippet',body='<h1>Snippets!</h1>')Update a Snippetapi.update_snippet('snp_1234asdf1234',name='My Snippet',body='<h1>Snippets!</h1>')Internationalization (i18n) APIGet translation package (.pot file)api.get_translation_template(`my_translation_tag`)Post translated strings and .po fileswithopen('my_translation_file','rb')asf:api.create_translation_file(`my_translation_tag`,f.read())RenderRender a Template with dataThe Render API allows you to render a template with data, using the exact same rendering workflow that Sendwithus uses when delivering your email.Strictis set toFalseas a default, ifStrict=Truethis API call will fail on any missingemail_data.api.render(email_id='YOUR-TEMPLATE-ID',email_data={'amount':'$12.00'},locale='fr-FR',version_name='French-Version',strict=False)Batch APISendwithus' API has abatch endpointthat can take multiple requests and execute them concurrently.Notethat Sendwithus recommends keeping batch requests to 10 items or less.Creating and Executing a Batch Requestapi=sendwithus.api('YOUR-API-KEY')batch=api.start_batch()emails=['user+1@example.com','user+2@example.com',# ...'user+10@example.com']# Generate the batch requestforemailinemails:batch.send(email_id='YOUR-TEMPLATE-ID',recipient={'address':email})printbatch.command_length()# show number of items in the batch requestresults=batch.execute()# returns a `requests` Response ObjectExpected ResponsesSuccess>>>r.status_code200>>>r.json().get('success')True>>>r.json().get('status')u'OK'>>>r.json().get('receipt_id')u'numeric-receipt-id'Error casesmalformed request>>>r.status_code400bad API key>>>r.status_code403Run TestsUsetoxto run the tests:toxTesting Multiple Python VersionsThis assumes you havetoxinstalled and usedpyenvto install multiple versions of python.Once all the supported python versions are installed simply run:toxThis will run the tests against all the versions specified intox.ini.TroubleshootingGeneral TroubleshootingEnable debug modeMake sure you're using the latest Python clientCapture the response data and check your logs — often this will have the exact errorEnable Debug ModeDebug mode prints out the underlying request information as well as the data payload that gets sent to Sendwithus. You will most likely find this information in your logs. To enable it, simply putDEBUG=Trueas a parameter when instantiating the API object. Use the debug mode to compare the data payload getting sent toSendwithus' API docs.importsendwithusapi=sendwithus.api(api_key='YOUR-API-KEY',DEBUG=True)Response RangesSendwithus' API typically sends responses back in these ranges:2xx &emdash; Successful Request4xx &emdash; Failed Request (Client error)5xx &emdash; Failed Request (Server error)If you're receiving an error in the 400 response range follow these steps:Double check the data and ID's getting passed to SendwithusEnsure your API key is correctLog and check the body of the responseInternalTo packagepythonsetup.pysdistbdist_wheelupload