Skip to content

Instantly share code, notes, and snippets.

@timfeirg
Created December 8, 2015 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timfeirg/b294b90260ffd3be977c to your computer and use it in GitHub Desktop.
Save timfeirg/b294b90260ffd3be977c to your computer and use it in GitHub Desktop.
simple wrapper for sendcloud
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: sendcloud
Author: timfeirg
Email: liuyifu@ricebook.com
Github: https://github.com/timfeirg/
Description: sendcloud python wrapper
"""
import requests
import six
def to_camel_case(snake_str):
components = snake_str.split('_')
# We capitalize the first letter of each component except the first one
# with the 'title' method and join them together.
return components[0] + ''.join(x.title() for x in components[1:])
class SendCloudClient(object):
# that sendcloud supports https across all their apis, is a lie
# send_mail_url = 'https://api.sendcloud.net/apiv2/mail/send'
send_mail_url = 'http://api.sendcloud.net/apiv2/mail/send'
def __init__(self, **kwargs):
"""
api_user, api_key, from_ -- str, suggested kwargs
see http://sendcloud.sohu.com/doc/email_v2/send_email/ for a list of
supported args, all kwargs are converted from snake case to lower camel
case
"""
self._default_payload = self.make_sendcloud_compatible_kwargs(kwargs)
@staticmethod
def make_sendcloud_compatible_kwargs(dic):
return dict((to_camel_case(k), v) for k, v in dic.items())
@staticmethod
def make_to_email_address(to_):
if isinstance(to_, six.string_types):
to_email_addr = to_
else:
to_email_addr = ';'.join(to_)
return to_email_addr
@property
def default_payload(self):
return self._default_payload.copy()
def send_email(self, to_, subject, **kwargs):
"""
to_ -- str or list of email address, if str, email addresses should be seperated by ';'
subject -- str
html or plain -- str, content will be html or plain
can have all kwargs overloaded
"""
payload = self.default_payload
to_email_addr = self.make_to_email_address(to_)
new_payload = self.make_sendcloud_compatible_kwargs(kwargs)
new_payload.update({'to': to_email_addr, 'subject': subject})
payload.update(new_payload)
res = requests.post(self.send_mail_url, data=payload, verify=True)
return res
SEND_CLOUD_CONFIG = {
'api_user': 'xxx',
'api_key': 'xxx',
'from_': 'xxx@xxx.com',
}
send_cloud_client = SendCloudClient(**SEND_CLOUD_CONFIG)
send_cloud_client.send_email('xxx@xxx.com', 'title', plain='content')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment