daily pastebin goal
74%
SHARE
TWEET

SendGrid API using

as_tsrpay Feb 13th, 2018 198 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # coding: utf-8
  2.  
  3. import sendgrid
  4. import json
  5. import os
  6.  
  7.  
  8. # Class for processing list for campaign in SendGrid service.
  9. class SendGridCampaignListProcessor:
  10.     def __init__(self, list_id, api_key=os.environ.get('SENDGRID_API_KEY')):
  11.         self.apikey = api_key
  12.         self.list_id = list_id
  13.         self.sg = None
  14.  
  15.     def init_sendgrid(self):
  16.         """
  17.        Init SendGrid API object.
  18.        :return: True if API key exists.
  19.        """
  20.         if not self.apikey:
  21.             return False
  22.         self.sg = sendgrid.SendGridAPIClient(apikey=self.apikey)
  23.         return True
  24.  
  25.     def add_recipient(self, *args, **kwargs):
  26.         """
  27.        Add new recipient for campaign.
  28.        At the moment this API method limit is 3 requests in 2 seconds.
  29.        :param args:
  30.        :param kwargs: recipient info fields. Filed 'email' is required.
  31.        :return: recipient id.
  32.        """
  33.         if 'email' not in kwargs:
  34.             print('Error. Email field is missing.')
  35.             return None
  36.         if not self.sg:
  37.             print('Error. Looks like API client not initialized.')
  38.             return None
  39.         data = [kwargs]
  40.         response = self.sg.client.contactdb.recipients.post(request_body=data)
  41.         if response.status_code != 201:
  42.             print('Error. Request failed.')
  43.             return None
  44.         if response.body:
  45.             response_result = json.loads(response.body.decode('utf-8'))
  46.             if 'error_count' in response_result and response_result['error_count'] > 0:
  47.                 for error in response_result['errors']:
  48.                     print(error['message'])
  49.                 return None
  50.             if 'persisted_recipients' not in response_result or not response_result['persisted_recipients']:
  51.                 print('Something wrong. Looks like recipient was not added.')
  52.                 return None
  53.             return response_result['persisted_recipients'][0]
  54.         return None
  55.  
  56.     def add_recipient_to_list(self, recipient_id):
  57.         """
  58.        Add exist recipient to list.
  59.        At the moment this API method limit is 1000 requests per second.
  60.        :param recipient_id: recipient's id, string.
  61.        :return: True is requests status is success.
  62.        """
  63.         if not recipient_id:
  64.             print('Error. Recipient id is missed.')
  65.             return False
  66.         if not self.list_id:
  67.             print('Error. Wrong list id.')
  68.             return False
  69.         if not self.sg:
  70.             print('Error. Looks like API client not initialized.')
  71.             return False
  72.         response = self.sg.client.contactdb.lists._(self.list_id).recipients._(recipient_id).post()
  73.         if response.status_code != 201:
  74.             print('Error. Request failed.')
  75.             return False
  76.         if response.body:
  77.             response_result = json.loads(response.body.decode('utf-8'))
  78.             if response_result and 'error_count' in response_result and response_result['error_count'] > 0:
  79.                 for error in response_result['errors']:
  80.                     print(error['message'])
  81.                 return False
  82.         return True
  83.  
  84.     def delete_recipients_from_list(self, recipient_ids):
  85.         """
  86.        Delete recepients from list.
  87.        :param recipient_ids: recipient's id, string or list of recipient ids.
  88.        :return: True if request status is success.
  89.        """
  90.         if not recipient_ids:
  91.             print('Error. Recipient ids are missed.')
  92.             return False
  93.         if not self.list_id:
  94.             print('Error. Wrong list id.')
  95.             return False
  96.         if not self.sg:
  97.             print('Error. Looks like API client not initialized.')
  98.             return False
  99.         data = recipient_ids if isinstance(recipient_ids, list) else [recipient_ids]
  100.         response = self.sg.client.contactdb.recipients.delete(request_body=data)
  101.         if response.status_code != 204:
  102.             print('Error. Request failed.')
  103.             return False
  104.         if response.body:
  105.             response_result = json.loads(response.body.decode('utf-8'))
  106.             if response_result and 'error_count' in response_result and response_result['error_count'] > 0:
  107.                 for error in response_result['errors']:
  108.                     print(error['message'])
  109.                 return False
  110.         return True
  111.  
  112.  
  113. if __name__ == '__main__':
  114.     sgcl_proc = SendGridCampaignListProcessor(
  115.         list_id=11,
  116.         api_key=''
  117.     )
  118.     sgcl_proc.init_sendgrid()
  119.     recipient = sgcl_proc.add_recipient(first_name='Vasily', last_name='Pupkin', email='lol@test.com')
  120.     if not recipient:
  121.         print('Error. Recipient was not added to SendGrid service.')
  122.         exit(0)
  123.     print('Recipient is added to SendGrid service.')
  124.     if sgcl_proc.add_recipient_to_list(recipient):
  125.         print('Recipient is added to list.')
  126.         if sgcl_proc.delete_recipients_from_list(recipient):
  127.             print('Recipient is deleted from list.')
RAW Paste Data
Top