From 46ecc632120a41e5367058905bcd79910b6f993a Mon Sep 17 00:00:00 2001 From: d grossman Date: Tue, 17 Oct 2017 10:38:54 -0700 Subject: [PATCH 01/45] Get unassigned IPs #392, made helper function --- sendgrid/helpers/endpoints/__init__.py | 0 sendgrid/helpers/endpoints/ip/__init__.py | 0 .../helpers/endpoints/ip/test_unassigned.py | 80 +++++++++++++++++++ sendgrid/helpers/endpoints/ip/unassigned.py | 52 ++++++++++++ 4 files changed, 132 insertions(+) create mode 100644 sendgrid/helpers/endpoints/__init__.py create mode 100644 sendgrid/helpers/endpoints/ip/__init__.py create mode 100644 sendgrid/helpers/endpoints/ip/test_unassigned.py create mode 100644 sendgrid/helpers/endpoints/ip/unassigned.py diff --git a/sendgrid/helpers/endpoints/__init__.py b/sendgrid/helpers/endpoints/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/sendgrid/helpers/endpoints/ip/__init__.py b/sendgrid/helpers/endpoints/ip/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/sendgrid/helpers/endpoints/ip/test_unassigned.py b/sendgrid/helpers/endpoints/ip/test_unassigned.py new file mode 100644 index 000000000..cc2af3b40 --- /dev/null +++ b/sendgrid/helpers/endpoints/ip/test_unassigned.py @@ -0,0 +1,80 @@ +import json +import pytest + +from .unassigned import unassigned + + +def test_unassigned_ip(): + + ret_json = '''[ { + "ip": "167.89.21.3", + "pools": [ + "pool1", + "pool2" + ], + "whitelabeled": false, + "start_date": 1409616000, + "subusers": [ + "tim@sendgrid.net" + ], + "warmup": false, + "assigned_at": 1482883200 + }, + { + "ip": "192.168.1.1", + "pools": [ + "pool1", + "pool2" + ], + "whitelabeled": false, + "start_date": 1409616000, + "subusers": [ + "tim@sendgrid.net" + ], + "warmup": false, + "assigned_at": 1482883200 + }, + { + "ip": "208.115.214.22", + "pools": [], + "whitelabeled": true, + "rdns": "o1.email.burgermail.com", + "start_date": 1409616000, + "subusers": [], + "warmup": false, + "assigned_at": 1482883200 + }, + { + "ip": "208.115.214.23", + "pools": [], + "whitelabeled": true, + "rdns": "o1.email.burgermail.com", + "start_date": 1409616000, + "subusers": [], + "warmup": false, + "assigned_at": 1482883200 + + } ] + ''' + + def get_all_ip(): + ret_val = json.loads(ret_json) + return ret_val + + data = {"208.115.214.23", "208.115.214.22"} + + as_json = True + calculated = unassigned(get_all_ip(), as_json=as_json) + calculated = json.loads(calculated) + + for item in calculated: + assert item["ip"] in data + + as_json = False + calculated = unassigned(get_all_ip(), as_json=as_json) + + for item in calculated: + assert item["ip"] in data + + calculated = unassigned(dict(), as_json=as_json) + assert calculated == [] diff --git a/sendgrid/helpers/endpoints/ip/unassigned.py b/sendgrid/helpers/endpoints/ip/unassigned.py new file mode 100644 index 000000000..075f19857 --- /dev/null +++ b/sendgrid/helpers/endpoints/ip/unassigned.py @@ -0,0 +1,52 @@ +import json + + +def format_ret(return_set, as_json=False): + """ decouple, allow for modifications to return type + returns a list of ip addresses in object or json form """ + ret_list = list() + for item in return_set: + d = {"ip": item} + ret_list.append(d) + + if as_json: + return json.dumps(ret_list) + + return ret_list + + +def unassigned(data, as_json=False): + """ https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses + The /ips rest endpoint returns information about the IP addresses + and the usernames assigned to an IP + + unassigned returns a listing of the IP addresses that are allocated + but have 0 usera assigned + + + data (response.body from sg.client.ips.get()) + as_json False -> get list of dicts + True -> get json object + + example: + sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + + params = {'subuser': 'test_string', 'ip': 'test_string', 'limit': 1, 'exclude_whitelabels': 'true', 'offset': 1} + response = sg.client.ips.get(query_params=params) + if response.status_code == 201: + data = response.body + unused = unassinged(data) """ + + no_subusers = set() + + if not isinstance(data, list): + return format_ret(no_subusers, as_json=as_json) + + for current in data: + num_subusers = len(current["subusers"]) + if num_subusers == 0: + current_ip = current["ip"] + no_subusers.add(current_ip) + + ret_val = format_ret(no_subusers, as_json=as_json) + return ret_val From 1fc5cbcbbf783c91050c2c6b061d73a092029bfd Mon Sep 17 00:00:00 2001 From: d grossman Date: Tue, 17 Oct 2017 10:45:29 -0700 Subject: [PATCH 02/45] break up tests --- .../helpers/endpoints/ip/test_unassigned.py | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/sendgrid/helpers/endpoints/ip/test_unassigned.py b/sendgrid/helpers/endpoints/ip/test_unassigned.py index cc2af3b40..a639f34a9 100644 --- a/sendgrid/helpers/endpoints/ip/test_unassigned.py +++ b/sendgrid/helpers/endpoints/ip/test_unassigned.py @@ -3,15 +3,12 @@ from .unassigned import unassigned - -def test_unassigned_ip(): - - ret_json = '''[ { - "ip": "167.89.21.3", +ret_json = '''[ { + "ip": "167.89.21.3", "pools": [ - "pool1", - "pool2" - ], + "pool1", + "pool2" + ], "whitelabeled": false, "start_date": 1409616000, "subusers": [ @@ -57,9 +54,13 @@ def test_unassigned_ip(): } ] ''' - def get_all_ip(): - ret_val = json.loads(ret_json) - return ret_val +def get_all_ip(): + ret_val = json.loads(ret_json) + return ret_val + + + +def test_unassigned_ip_json(): data = {"208.115.214.23", "208.115.214.22"} @@ -70,11 +71,17 @@ def get_all_ip(): for item in calculated: assert item["ip"] in data +def test_unassigned_ip_obj(): + + data = {"208.115.214.23", "208.115.214.22"} + as_json = False calculated = unassigned(get_all_ip(), as_json=as_json) for item in calculated: assert item["ip"] in data +def test_unassigned_baddata(): + as_json = False calculated = unassigned(dict(), as_json=as_json) assert calculated == [] From 56551f3a81d78a6ae5b44524024c29fa0c5a6af6 Mon Sep 17 00:00:00 2001 From: d grossman Date: Tue, 17 Oct 2017 10:53:21 -0700 Subject: [PATCH 03/45] make the python2.6 travis build happy --- sendgrid/helpers/endpoints/ip/test_unassigned.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/sendgrid/helpers/endpoints/ip/test_unassigned.py b/sendgrid/helpers/endpoints/ip/test_unassigned.py index a639f34a9..be5904018 100644 --- a/sendgrid/helpers/endpoints/ip/test_unassigned.py +++ b/sendgrid/helpers/endpoints/ip/test_unassigned.py @@ -59,10 +59,17 @@ def get_all_ip(): return ret_val +def make_data(): + data = set() + data.add("208.115.214.23") + data.add("208.115.214.22") + return data + + def test_unassigned_ip_json(): - data = {"208.115.214.23", "208.115.214.22"} + data = make_data() as_json = True calculated = unassigned(get_all_ip(), as_json=as_json) @@ -73,7 +80,7 @@ def test_unassigned_ip_json(): def test_unassigned_ip_obj(): - data = {"208.115.214.23", "208.115.214.22"} + data = make_data() as_json = False calculated = unassigned(get_all_ip(), as_json=as_json) From c05205afed6adca1cad03192ee08ad1cae4aafc9 Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Sun, 22 Oct 2017 10:11:27 +0800 Subject: [PATCH 04/45] Add global stats helper --- examples/helpers/stats/stats_example.py | 27 +++++++ sendgrid/helpers/stats/README.md | 1 + sendgrid/helpers/stats/__init__.py | 1 + sendgrid/helpers/stats/stats.py | 98 +++++++++++++++++++++++++ 4 files changed, 127 insertions(+) create mode 100644 examples/helpers/stats/stats_example.py create mode 100644 sendgrid/helpers/stats/README.md create mode 100644 sendgrid/helpers/stats/__init__.py create mode 100644 sendgrid/helpers/stats/stats.py diff --git a/examples/helpers/stats/stats_example.py b/examples/helpers/stats/stats_example.py new file mode 100644 index 000000000..3d2846e11 --- /dev/null +++ b/examples/helpers/stats/stats_example.py @@ -0,0 +1,27 @@ +import json +import os +from sendgrid.helpers.stats import * +from sendgrid import * + +# NOTE: you will need move this file to the root directory of this project to execute properly. + + +def build_global_stats(): + global_stats = Stats() + global_stats.start_date = '2017-10-14' + global_stats.end_date = '2017-10-20' + global_stats.aggregated_by = 'day' + return global_stats.get() + + +def get_global_stats(): + # Assumes you set your environment variable: + # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key + sg = SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + stats_params = build_global_stats() + response = sg.client.stats.get(query_params=stats_params) + print(response.status_code) + print(response.headers) + print(json.dumps(json.loads(response.body), indent=4, sort_keys=True)) + +get_global_stats() \ No newline at end of file diff --git a/sendgrid/helpers/stats/README.md b/sendgrid/helpers/stats/README.md new file mode 100644 index 000000000..2c062c3be --- /dev/null +++ b/sendgrid/helpers/stats/README.md @@ -0,0 +1 @@ +**This helper allows you to quickly and easily build a Stats object for sending your email stats to a database.** \ No newline at end of file diff --git a/sendgrid/helpers/stats/__init__.py b/sendgrid/helpers/stats/__init__.py new file mode 100644 index 000000000..9ee4dcdd8 --- /dev/null +++ b/sendgrid/helpers/stats/__init__.py @@ -0,0 +1 @@ +from .stats import * # noqa diff --git a/sendgrid/helpers/stats/stats.py b/sendgrid/helpers/stats/stats.py new file mode 100644 index 000000000..398fe7583 --- /dev/null +++ b/sendgrid/helpers/stats/stats.py @@ -0,0 +1,98 @@ +import json +import csv + + +class Stats(object): + def __init__( + self, start_date=None): + self._start_date = None + self._end_date = None + self._aggregated_by = None + self._sort_by_metric = None + self._sort_by_direction = None + self._limit = None + self._offset = None + + # Minimum required for stats + if start_date: + self.start_date = start_date + + def __str__(self): + return str(self.get()) + + def get(self): + """ + :return: response stats dict + """ + stats = {} + if self.start_date is not None: + stats["start_date"] = self.start_date + if self.end_date is not None: + stats["end_date"] = self.end_date + if self.aggregated_by is not None: + stats["aggregated_by"] = self.aggregated_by + if self.sort_by_metric is not None: + stats["sort_by_metric"] = self.sort_by_metric + if self.sort_by_direction is not None: + stats["sort_by_direction"] = self.sort_by_direction + if self.limit is not None: + stats["limit"] = self.limit + if self.offset is not None: + stats["offset"] = self.offset + return stats + + @property + def start_date(self): + return self._start_date + + @start_date.setter + def start_date(self, value): + self._start_date = value + + @property + def end_date(self): + return self._end_date + + @end_date.setter + def end_date(self, value): + self._end_date = value + + @property + def aggregated_by(self): + return self._aggregated_by + + @aggregated_by.setter + def aggregated_by(self, value): + self._aggregated_by = value + + @property + def sort_by_metric(self): + return self._sort_by_metric + + @sort_by_metric.setter + def sort_by_metric(self, value): + self._sort_by_metric = value + + @property + def sort_by_direction(self): + return self._sort_by_direction + + @sort_by_direction.setter + def sort_by_direction(self, value): + self._sort_by_direction = value + + @property + def limit(self): + return self._limit + + @limit.setter + def limit(self, value): + self._limit = value + + @property + def offset(self): + return self._offset + + @offset.setter + def offset(self, value): + self._offset = value From bdbd004b49c1fd9be3e70deb94b4b1dcc906902c Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Sun, 22 Oct 2017 12:52:30 +0800 Subject: [PATCH 05/45] Add child class CategoryStats --- examples/helpers/stats/stats_example.py | 44 +++++++++++++++-- sendgrid/helpers/stats/stats.py | 64 ++++++++++++++++++++++++- 2 files changed, 103 insertions(+), 5 deletions(-) diff --git a/examples/helpers/stats/stats_example.py b/examples/helpers/stats/stats_example.py index 3d2846e11..8688440d4 100644 --- a/examples/helpers/stats/stats_example.py +++ b/examples/helpers/stats/stats_example.py @@ -5,6 +5,10 @@ # NOTE: you will need move this file to the root directory of this project to execute properly. +# Assumes you set your environment variable: +# https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key +sg = SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + def build_global_stats(): global_stats = Stats() @@ -14,14 +18,46 @@ def build_global_stats(): return global_stats.get() +def build_category_stats(): + category_stats = CategoryStats() + category_stats.start_date = '2017-10-15' + category_stats.add_category(Category("foo")) + category_stats.add_category(Category("bar")) + return category_stats.get() + + +def build_category_stats_sums(): + category_stats = CategoryStats() + category_stats.start_date = '2017-10-15' + category_stats.limit = 5 + category_stats.offset = 1 + return category_stats.get() + + def get_global_stats(): - # Assumes you set your environment variable: - # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key - sg = SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) stats_params = build_global_stats() response = sg.client.stats.get(query_params=stats_params) + response_body = json.loads(response.body)[0]['date'] + print(response.status_code) + print(response.headers) + print(json.dumps(response_body, indent=4, sort_keys=True)) + + +def get_category_stats(): + stats_params = build_category_stats() + response = sg.client.categories.stats.get(query_params=stats_params) + print(response.status_code) + print(response.headers) + print(json.dumps(json.loads(response.body), indent=4, sort_keys=True)) + + +def get_category_stats_sums(): + stats_params = build_category_stats_sums() + response = sg.client.categories.stats.sums.get(query_params=stats_params) print(response.status_code) print(response.headers) print(json.dumps(json.loads(response.body), indent=4, sort_keys=True)) -get_global_stats() \ No newline at end of file +get_global_stats() +get_category_stats() +get_category_stats_sums() diff --git a/sendgrid/helpers/stats/stats.py b/sendgrid/helpers/stats/stats.py index 398fe7583..8719a9f7d 100644 --- a/sendgrid/helpers/stats/stats.py +++ b/sendgrid/helpers/stats/stats.py @@ -1,7 +1,6 @@ import json import csv - class Stats(object): def __init__( self, start_date=None): @@ -96,3 +95,66 @@ def offset(self): @offset.setter def offset(self, value): self._offset = value + + +class CategoryStats(Stats): + def __init__(self, start_date=None, categories=None): + self._categories = None + super(CategoryStats, self).__init__() + + # Minimum required for category stats + if start_date and categories: + self.start_date = start_date + self.categories = categories + + def get(self): + """ + :return: response stats dict + """ + stats = {} + if self.start_date is not None: + stats["start_date"] = self.start_date + if self.end_date is not None: + stats["end_date"] = self.end_date + if self.aggregated_by is not None: + stats["aggregated_by"] = self.aggregated_by + if self.sort_by_metric is not None: + stats["sort_by_metric"] = self.sort_by_metric + if self.sort_by_direction is not None: + stats["sort_by_direction"] = self.sort_by_direction + if self.limit is not None: + stats["limit"] = self.limit + if self.offset is not None: + stats["offset"] = self.offset + if self.categories is not None: + stats['categories'] = [category.get() for category in + self.categories] + return stats + + @property + def categories(self): + return self._categories + + def add_category(self, category): + if self._categories is None: + self._categories = [] + self._categories.append(category) + + +class Category(object): + + def __init__(self, name=None): + self._name = None + if name is not None: + self._name = name + + @property + def name(self): + return self._name + + @name.setter + def name(self, value): + self._name = value + + def get(self): + return self.name \ No newline at end of file From c0fdaffd823f3e5ee5b0f0757dc0a8c4285069ae Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Sun, 22 Oct 2017 12:53:10 +0800 Subject: [PATCH 06/45] fix typo --- examples/helpers/stats/stats_example.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/helpers/stats/stats_example.py b/examples/helpers/stats/stats_example.py index 8688440d4..3862b2097 100644 --- a/examples/helpers/stats/stats_example.py +++ b/examples/helpers/stats/stats_example.py @@ -37,10 +37,9 @@ def build_category_stats_sums(): def get_global_stats(): stats_params = build_global_stats() response = sg.client.stats.get(query_params=stats_params) - response_body = json.loads(response.body)[0]['date'] print(response.status_code) print(response.headers) - print(json.dumps(response_body, indent=4, sort_keys=True)) + print(json.dumps(json.loads(response.body), indent=4, sort_keys=True)) def get_category_stats(): From 9f1e23144ed39f2ee12cbf04b37928dd6bbbfc9e Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Sun, 22 Oct 2017 13:04:20 +0800 Subject: [PATCH 07/45] Clean up json and refine CategoryStats Class --- examples/helpers/stats/stats_example.py | 19 ++++++++++++------- sendgrid/helpers/stats/stats.py | 3 ++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/examples/helpers/stats/stats_example.py b/examples/helpers/stats/stats_example.py index 3862b2097..41f4b85ab 100644 --- a/examples/helpers/stats/stats_example.py +++ b/examples/helpers/stats/stats_example.py @@ -10,6 +10,10 @@ sg = SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) +def pprint_json(json_raw): + print(json.dumps(json.loads(json_raw), indent=4, sort_keys=True)) + + def build_global_stats(): global_stats = Stats() global_stats.start_date = '2017-10-14' @@ -19,10 +23,10 @@ def build_global_stats(): def build_category_stats(): - category_stats = CategoryStats() - category_stats.start_date = '2017-10-15' - category_stats.add_category(Category("foo")) - category_stats.add_category(Category("bar")) + category_stats = CategoryStats('2017-10-15', ['foo', 'bar']) + # category_stats.start_date = '2017-10-15' + # category_stats.add_category(Category("foo")) + # category_stats.add_category(Category("bar")) return category_stats.get() @@ -39,15 +43,16 @@ def get_global_stats(): response = sg.client.stats.get(query_params=stats_params) print(response.status_code) print(response.headers) - print(json.dumps(json.loads(response.body), indent=4, sort_keys=True)) + pprint_json(response.body) def get_category_stats(): stats_params = build_category_stats() + print(stats_params) response = sg.client.categories.stats.get(query_params=stats_params) print(response.status_code) print(response.headers) - print(json.dumps(json.loads(response.body), indent=4, sort_keys=True)) + pprint_json(response.body) def get_category_stats_sums(): @@ -55,7 +60,7 @@ def get_category_stats_sums(): response = sg.client.categories.stats.sums.get(query_params=stats_params) print(response.status_code) print(response.headers) - print(json.dumps(json.loads(response.body), indent=4, sort_keys=True)) + pprint_json(response.body) get_global_stats() get_category_stats() diff --git a/sendgrid/helpers/stats/stats.py b/sendgrid/helpers/stats/stats.py index 8719a9f7d..b5ddebcc1 100644 --- a/sendgrid/helpers/stats/stats.py +++ b/sendgrid/helpers/stats/stats.py @@ -105,7 +105,8 @@ def __init__(self, start_date=None, categories=None): # Minimum required for category stats if start_date and categories: self.start_date = start_date - self.categories = categories + for cat in categories: + self.add_category(Category(cat)) def get(self): """ From d36ff2bcbee3ff17801af2506eb8e887c3fdaa1d Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Sun, 22 Oct 2017 13:41:53 +0800 Subject: [PATCH 08/45] Add SubuserStats class --- examples/helpers/stats/stats_example.py | 42 +++++++++++++-- sendgrid/helpers/stats/stats.py | 70 +++++++++++++++++++++++-- 2 files changed, 102 insertions(+), 10 deletions(-) diff --git a/examples/helpers/stats/stats_example.py b/examples/helpers/stats/stats_example.py index 41f4b85ab..00a704c47 100644 --- a/examples/helpers/stats/stats_example.py +++ b/examples/helpers/stats/stats_example.py @@ -11,7 +11,7 @@ def pprint_json(json_raw): - print(json.dumps(json.loads(json_raw), indent=4, sort_keys=True)) + print(json.dumps(json.loads(json_raw), indent=2, sort_keys=True)) def build_global_stats(): @@ -38,6 +38,21 @@ def build_category_stats_sums(): return category_stats.get() +def build_subuser_stats(): + subuser_stats = SubuserStats('2017-10-20', ['aaronmakks','foo']) + # subuser_stats.start_date = '2017-10-15' + # subuser_stats.add_subuser(Subuser("foo")) + # subuser_stats.add_subuser(Subuser("bar")) + return subuser_stats.get() + +def build_subuser_stats_sums(): + subuser_stats = SubuserStats() + subuser_stats.start_date = '2017-10-15' + subuser_stats.limit = 5 + subuser_stats.offset = 1 + return subuser_stats.get() + + def get_global_stats(): stats_params = build_global_stats() response = sg.client.stats.get(query_params=stats_params) @@ -48,7 +63,6 @@ def get_global_stats(): def get_category_stats(): stats_params = build_category_stats() - print(stats_params) response = sg.client.categories.stats.get(query_params=stats_params) print(response.status_code) print(response.headers) @@ -62,6 +76,24 @@ def get_category_stats_sums(): print(response.headers) pprint_json(response.body) -get_global_stats() -get_category_stats() -get_category_stats_sums() + +def get_subuser_stats(): + stats_params = build_subuser_stats() + response = sg.client.subusers.stats.get(query_params=stats_params) + print(response.status_code) + print(response.headers) + pprint_json(response.body) + + +def get_subuser_stats_sums(): + stats_params = build_subuser_stats_sums() + response = sg.client.subusers.stats.sums.get(query_params=stats_params) + print(response.status_code) + print(response.headers) + pprint_json(response.body) + +# get_global_stats() +# get_category_stats() +# get_category_stats_sums() +# get_subuser_stats() +# get_subuser_stats_sums() diff --git a/sendgrid/helpers/stats/stats.py b/sendgrid/helpers/stats/stats.py index b5ddebcc1..550599138 100644 --- a/sendgrid/helpers/stats/stats.py +++ b/sendgrid/helpers/stats/stats.py @@ -1,6 +1,3 @@ -import json -import csv - class Stats(object): def __init__( self, start_date=None): @@ -105,8 +102,8 @@ def __init__(self, start_date=None, categories=None): # Minimum required for category stats if start_date and categories: self.start_date = start_date - for cat in categories: - self.add_category(Category(cat)) + for cat_name in categories: + self.add_category(Category(cat_name)) def get(self): """ @@ -142,8 +139,71 @@ def add_category(self, category): self._categories.append(category) +class SubuserStats(Stats): + def __init__(self, start_date=None, subusers=None): + self._subusers = None + super(SubuserStats, self).__init__() + + # Minimum required for subusers stats + if start_date and subusers: + self.start_date = start_date + for subuser_name in subusers: + self.add_subuser(Subuser(subuser_name)) + + def get(self): + """ + :return: response stats dict + """ + stats = {} + if self.start_date is not None: + stats["start_date"] = self.start_date + if self.end_date is not None: + stats["end_date"] = self.end_date + if self.aggregated_by is not None: + stats["aggregated_by"] = self.aggregated_by + if self.sort_by_metric is not None: + stats["sort_by_metric"] = self.sort_by_metric + if self.sort_by_direction is not None: + stats["sort_by_direction"] = self.sort_by_direction + if self.limit is not None: + stats["limit"] = self.limit + if self.offset is not None: + stats["offset"] = self.offset + if self.subusers is not None: + stats['subusers'] = [subuser.get() for subuser in + self.subusers] + return stats + + @property + def subusers(self): + return self._subusers + + def add_subuser(self, subuser): + if self._subusers is None: + self._subusers = [] + self._subusers.append(subuser) + + class Category(object): + def __init__(self, name=None): + self._name = None + if name is not None: + self._name = name + + @property + def name(self): + return self._name + + @name.setter + def name(self, value): + self._name = value + + def get(self): + return self.name + +class Subuser(object): + def __init__(self, name=None): self._name = None if name is not None: From 7d919237508b81db14ac51a997698d7ea50db194 Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Sun, 22 Oct 2017 13:54:56 +0800 Subject: [PATCH 09/45] Add to readme --- sendgrid/helpers/stats/README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/sendgrid/helpers/stats/README.md b/sendgrid/helpers/stats/README.md index 2c062c3be..1fe31558b 100644 --- a/sendgrid/helpers/stats/README.md +++ b/sendgrid/helpers/stats/README.md @@ -1 +1,10 @@ -**This helper allows you to quickly and easily build a Stats object for sending your email stats to a database.** \ No newline at end of file +**This helper allows you to quickly and easily build a Stats object for sending your email stats to a database.** + +# Quick Start + +Run the [example](https://github.com/sendgrid/sendgrid-python/tree/master/examples/helpers/stats) (make sure you have set your environment variable to include your SENDGRID_API_KEY). + +## Usage + +- See the [examples](https://github.com/sendgrid/sendgrid-python/tree/master/examples/helpers/stats) for complete working examples. +- [Documentation](https://sendgrid.com/docs/API_Reference/Web_API_v3/Stats/index.html) \ No newline at end of file From 55bd15d73b041cfc60f4e59a6404d16a433a622c Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Fri, 27 Oct 2017 08:15:56 +0800 Subject: [PATCH 10/45] add tests for stats helper --- examples/helpers/stats/stats_example.py | 10 ++-- sendgrid/helpers/stats/stats.py | 3 +- test/test_stats.py | 79 +++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 6 deletions(-) create mode 100644 test/test_stats.py diff --git a/examples/helpers/stats/stats_example.py b/examples/helpers/stats/stats_example.py index 00a704c47..d48664c3f 100644 --- a/examples/helpers/stats/stats_example.py +++ b/examples/helpers/stats/stats_example.py @@ -92,8 +92,8 @@ def get_subuser_stats_sums(): print(response.headers) pprint_json(response.body) -# get_global_stats() -# get_category_stats() -# get_category_stats_sums() -# get_subuser_stats() -# get_subuser_stats_sums() +get_global_stats() +get_category_stats() +get_category_stats_sums() +get_subuser_stats() +get_subuser_stats_sums() diff --git a/sendgrid/helpers/stats/stats.py b/sendgrid/helpers/stats/stats.py index 550599138..8fe1399a2 100644 --- a/sendgrid/helpers/stats/stats.py +++ b/sendgrid/helpers/stats/stats.py @@ -202,6 +202,7 @@ def name(self, value): def get(self): return self.name + class Subuser(object): def __init__(self, name=None): @@ -218,4 +219,4 @@ def name(self, value): self._name = value def get(self): - return self.name \ No newline at end of file + return self.name diff --git a/test/test_stats.py b/test/test_stats.py new file mode 100644 index 000000000..eafd131db --- /dev/null +++ b/test/test_stats.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +import json +from sendgrid.helpers.stats import * + +try: + import unittest2 as unittest +except ImportError: + import unittest + + +class UnitTests(unittest.TestCase): + + def test_basicStats(self): + + """Minimum required for stats""" + global_stats = Stats(start_date='12-09-2017') + + self.assertEqual( + json.dumps( + global_stats.get(), + sort_keys=True), + '{"start_date": "12-09-2017"}' + ) + + self.assertTrue(isinstance(str(global_stats), str)) + + def test_Stats(self): + + all_stats = Stats(start_date='12-09-2017') + all_stats.end_date = '12-10-2017' + all_stats.aggregated_by = 'day' + all_stats._sort_by_direction = 'asc' + all_stats._limit = 100 + all_stats._offset = 2 + + self.assertEqual( + json.dumps( + all_stats.get(), + sort_keys=True), + '{"aggregated_by": "day", "end_date": "12-10-2017", ' + '"limit": 100, "offset": 2, "sort_by_direction": "asc", ' + '"start_date": "12-09-2017"}' + ) + + def test_categoryStats(self): + + category_stats = CategoryStats(start_date='12-09-2017', categories=['foo', 'bar']) + category_stats.end_date = '12-10-2017' + category_stats.aggregated_by = 'day' + category_stats._sort_by_direction = 'asc' + category_stats._limit = 100 + category_stats._offset = 2 + + self.assertEqual( + json.dumps( + category_stats.get(), + sort_keys=True), + '{"aggregated_by": "day", "categories": ["foo", "bar"], ' + '"end_date": "12-10-2017", "limit": 100, "offset": 2, ' + '"sort_by_direction": "asc", "start_date": "12-09-2017"}' + ) + + def test_subuserStats(self): + + subuser_stats = SubuserStats(start_date = '12-09-2017', subusers=['foo', 'bar']) + subuser_stats.end_date = '12-10-2017' + subuser_stats.aggregated_by = 'day' + subuser_stats._sort_by_direction = 'asc' + subuser_stats._limit = 100 + subuser_stats._offset = 2 + + self.assertEqual( + json.dumps( + subuser_stats.get(), + sort_keys=True), + '{"aggregated_by": "day", "end_date": "12-10-2017", ' + '"limit": 100, "offset": 2, "sort_by_direction": "asc", ' + '"start_date": "12-09-2017", "subusers": ["foo", "bar"]}' + ) From f765e4a93f3d1f9288d6374cba16e756453d1866 Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Fri, 27 Oct 2017 08:43:37 +0800 Subject: [PATCH 11/45] Add more tests --- test/test_stats.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/test_stats.py b/test/test_stats.py index eafd131db..7da54b2e2 100644 --- a/test/test_stats.py +++ b/test/test_stats.py @@ -45,6 +45,7 @@ def test_Stats(self): def test_categoryStats(self): category_stats = CategoryStats(start_date='12-09-2017', categories=['foo', 'bar']) + category_stats.add_category(Category('woo')) category_stats.end_date = '12-10-2017' category_stats.aggregated_by = 'day' category_stats._sort_by_direction = 'asc' @@ -55,7 +56,7 @@ def test_categoryStats(self): json.dumps( category_stats.get(), sort_keys=True), - '{"aggregated_by": "day", "categories": ["foo", "bar"], ' + '{"aggregated_by": "day", "categories": ["foo", "bar", "woo"], ' '"end_date": "12-10-2017", "limit": 100, "offset": 2, ' '"sort_by_direction": "asc", "start_date": "12-09-2017"}' ) @@ -63,6 +64,7 @@ def test_categoryStats(self): def test_subuserStats(self): subuser_stats = SubuserStats(start_date = '12-09-2017', subusers=['foo', 'bar']) + subuser_stats.add_subuser(Subuser('blah')) subuser_stats.end_date = '12-10-2017' subuser_stats.aggregated_by = 'day' subuser_stats._sort_by_direction = 'asc' @@ -75,5 +77,5 @@ def test_subuserStats(self): sort_keys=True), '{"aggregated_by": "day", "end_date": "12-10-2017", ' '"limit": 100, "offset": 2, "sort_by_direction": "asc", ' - '"start_date": "12-09-2017", "subusers": ["foo", "bar"]}' + '"start_date": "12-09-2017", "subusers": ["foo", "bar", "blah"]}' ) From edc5e045feb2384cfbf6bb64d22e27618de65174 Mon Sep 17 00:00:00 2001 From: Aaron Mak Kang Sheng Date: Fri, 27 Oct 2017 22:47:18 +0800 Subject: [PATCH 12/45] add more tests --- test/test_stats.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/test/test_stats.py b/test/test_stats.py index 7da54b2e2..c71117397 100644 --- a/test/test_stats.py +++ b/test/test_stats.py @@ -30,6 +30,7 @@ def test_Stats(self): all_stats.end_date = '12-10-2017' all_stats.aggregated_by = 'day' all_stats._sort_by_direction = 'asc' + all_stats.sort_by_metric = 'clicks' all_stats._limit = 100 all_stats._offset = 2 @@ -39,7 +40,7 @@ def test_Stats(self): sort_keys=True), '{"aggregated_by": "day", "end_date": "12-10-2017", ' '"limit": 100, "offset": 2, "sort_by_direction": "asc", ' - '"start_date": "12-09-2017"}' + '"sort_by_metric": "clicks", "start_date": "12-09-2017"}' ) def test_categoryStats(self): @@ -49,6 +50,7 @@ def test_categoryStats(self): category_stats.end_date = '12-10-2017' category_stats.aggregated_by = 'day' category_stats._sort_by_direction = 'asc' + category_stats.sort_by_metric = 'clicks' category_stats._limit = 100 category_stats._offset = 2 @@ -58,7 +60,8 @@ def test_categoryStats(self): sort_keys=True), '{"aggregated_by": "day", "categories": ["foo", "bar", "woo"], ' '"end_date": "12-10-2017", "limit": 100, "offset": 2, ' - '"sort_by_direction": "asc", "start_date": "12-09-2017"}' + '"sort_by_direction": "asc", "sort_by_metric": "clicks", ' + '"start_date": "12-09-2017"}' ) def test_subuserStats(self): @@ -68,6 +71,7 @@ def test_subuserStats(self): subuser_stats.end_date = '12-10-2017' subuser_stats.aggregated_by = 'day' subuser_stats._sort_by_direction = 'asc' + subuser_stats.sort_by_metric = 'clicks' subuser_stats._limit = 100 subuser_stats._offset = 2 @@ -77,5 +81,6 @@ def test_subuserStats(self): sort_keys=True), '{"aggregated_by": "day", "end_date": "12-10-2017", ' '"limit": 100, "offset": 2, "sort_by_direction": "asc", ' - '"start_date": "12-09-2017", "subusers": ["foo", "bar", "blah"]}' + '"sort_by_metric": "clicks", "start_date": "12-09-2017", ' + '"subusers": ["foo", "bar", "blah"]}' ) From 7600f8393dd58417e4c2a0e05ca2f4ed18cc076d Mon Sep 17 00:00:00 2001 From: navinpai Date: Sun, 29 Oct 2017 00:28:24 +0530 Subject: [PATCH 13/45] Add slack event integration --- USE_CASES.md | 322 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 322 insertions(+) create mode 100644 USE_CASES.md diff --git a/USE_CASES.md b/USE_CASES.md new file mode 100644 index 000000000..b59981e19 --- /dev/null +++ b/USE_CASES.md @@ -0,0 +1,322 @@ +This documentation provides examples for specific use cases. Please [open an issue](https://github.com/sendgrid/sendgrid-python/issues) or make a pull request for any use cases you would like us to document here. Thank you! + +# Table of Contents + +* [Transactional Templates](#transactional-templates) +* [Attachment](#attachment) +* [How to Setup a Domain Whitelabel](#domain_whitelabel) +* [How to View Email Statistics](#email_stats) +* [Asynchronous Mail Send](#asynchronous-mail-send) +* [Slack Event API Integration](#slack_event_integration) + + +# Transactional Templates + +For this example, we assume you have created a [transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). Following is the template content we used for testing. + +Template ID (replace with your own): + +```text +13b8f94f-bcae-4ec6-b752-70d6cb59f932 +``` + +Email Subject: + +```text +<%subject%> +``` + +Template Body: + +```html + + + + + +Hello -name-, +

+I'm glad you are trying out the template feature! +

+<%body%> +

+I hope you are having a great day in -city- :) +

+ + +``` + +## With Mail Helper Class + +```python +import sendgrid +import os +from sendgrid.helpers.mail import Email, Content, Substitution, Mail +try: + # Python 3 + import urllib.request as urllib +except ImportError: + # Python 2 + import urllib2 as urllib + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) +from_email = Email("test@example.com") +subject = "I'm replacing the subject tag" +to_email = Email("test@example.com") +content = Content("text/html", "I'm replacing the body tag") +mail = Mail(from_email, subject, to_email, content) +mail.personalizations[0].add_substitution(Substitution("-name-", "Example User")) +mail.personalizations[0].add_substitution(Substitution("-city-", "Denver")) +mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932" +try: + response = sg.client.mail.send.post(request_body=mail.get()) +except urllib.HTTPError as e: + print (e.read()) + exit() +print(response.status_code) +print(response.body) +print(response.headers) +``` + +## Without Mail Helper Class + +```python +import sendgrid +import os +try: + # Python 3 + import urllib.request as urllib +except ImportError: + # Python 2 + import urllib2 as urllib + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) +data = { + "personalizations": [ + { + "to": [ + { + "email": "test@example.com" + } + ], + "substitutions": { + "-name-": "Example User", + "-city-": "Denver" + }, + "subject": "I'm replacing the subject tag" + }, + ], + "from": { + "email": "test@example.com" + }, + "content": [ + { + "type": "text/html", + "value": "I'm replacing the body tag" + } + ], + "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932" +} +try: + response = sg.client.mail.send.post(request_body=data) +except urllib.HTTPError as e: + print (e.read()) + exit() +print(response.status_code) +print(response.body) +print(response.headers) +``` + + +# Attachment + +```python +import base64 +import sendgrid +import os +from sendgrid.helpers.mail import Email, Content, Mail, Attachment +try: + # Python 3 + import urllib.request as urllib +except ImportError: + # Python 2 + import urllib2 as urllib + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) +from_email = Email("test@example.com") +subject = "subject" +to_email = Email("to_email@example.com") +content = Content("text/html", "I'm a content example") + +file_path = "file_path.pdf" +with open(file_path,'rb') as f: + data = f.read() + f.close() +encoded = base64.b64encode(data).decode() + +attachment = Attachment() +attachment.content = encoded +attachment.type = "application/pdf" +attachment.filename = "test.pdf" +attachment.disposition = "attachment" +attachment.content_id = "Example Content ID" + +mail = Mail(from_email, subject, to_email, content) +mail.add_attachment(attachment) +try: + response = sg.client.mail.send.post(request_body=mail.get()) +except urllib.HTTPError as e: + print(e.read()) + exit() + +print(response.status_code) +print(response.body) +print(response.headers) +``` + + +# How to Setup a Domain Whitelabel + +You can find documentation for how to setup a domain whitelabel via the UI [here](https://sendgrid.com/docs/Classroom/Basics/Whitelabel/setup_domain_whitelabel.html) and via API [here](https://github.com/sendgrid/sendgrid-python/blob/master/USAGE.md#whitelabel). + +Find more information about all of SendGrid's whitelabeling related documentation [here](https://sendgrid.com/docs/Classroom/Basics/Whitelabel/index.html). + + +# How to View Email Statistics + +You can find documentation for how to view your email statistics via the UI [here](https://app.sendgrid.com/statistics) and via API [here](https://github.com/sendgrid/sendgrid-python/blob/master/USAGE.md#stats). + +Alternatively, we can post events to a URL of your choice via our [Event Webhook](https://sendgrid.com/docs/API_Reference/Webhooks/event.html) about events that occur as SendGrid processes your email. + + +# Asynchronous Mail Send + +## Using `asyncio` (3.5+) + +The built-in `asyncio` library can be used to send email in a non-blocking manner. `asyncio` helps us execute mail sending in a separate context, allowing us to continue execution of business logic without waiting for all our emails to send first. + +```python +import sendgrid +from sendgrid.helpers.mail import * +import os +import asyncio + + +sg = sendgrid.SendGridAPIClient( + apikey=os.getenv("SENDGRID_API_KEY") +) + +from_email = Email("test@example.com") +to_email = Email("test1@example.com") + +content = Content("text/plain", "This is asynchronous sending test.") + +# instantiate `sendgrid.helpers.mail.Mail` objects +em1 = Mail(from_email, "Message #1", to_email, content) +em2 = Mail(from_email, "Message #2", to_email, content) +em3 = Mail(from_email, "Message #3", to_email, content) +em4 = Mail(from_email, "Message #4", to_email, content) +em5 = Mail(from_email, "Message #5", to_email, content) +em6 = Mail(from_email, "Message #6", to_email, content) +em7 = Mail(from_email, "Message #7", to_email, content) +em8 = Mail(from_email, "Message #8", to_email, content) +em9 = Mail(from_email, "Message #9", to_email, content) +em10 = Mail(from_email, "Message #10", to_email, content) + + +ems = [em1, em2, em3, em4, em5, em6, em7, em8, em9, em10] + + +async def send_email(n, email): + ''' + send_mail wraps SendGrid's API client, and makes a POST request to + the api/v3/mail/send endpoint with `email`. + Args: + email: single mail object. + ''' + try: + response = sg.client.mail.send.post(request_body=email.get()) + if response.status_code < 300: + print("Email #{} processed".format(n), response.body, response.status_code) + except urllib.error.HTTPError as e: + e.read() + + +@asyncio.coroutine +def send_many(emails, cb): + ''' + send_many creates a number of non-blocking tasks (to send email) + that will run on the existing event loop. Due to non-blocking nature, + you can include a callback that will run after all tasks have been queued. + + Args: + emails: contains any # of `sendgrid.helpers.mail.Mail`. + cb: a function that will execute immediately. + ''' + print("START - sending emails ...") + for n, em in enumerate(emails): + asyncio.async(send_email(n, em)) + print("END - returning control...") + cb() + + +def sample_cb(): + print("Executing callback now...") + for i in range(0, 100): + print(i) + return + + +if __name__ == "__main__": + loop = asyncio.get_event_loop() + task = asyncio.async(send_many(ems, sample_cb)) + loop.run_until_complete(task) +``` + + +# Integrate with Slack Events API + +It's fairly straightforward to integrate Sendgrid with Slack, to allow emails to be triggered by events happening on Slack. + +For this, we make use of the [Official Slack Events API](https://github.com/slackapi/python-slack-events-api), which can be installed using pip. + +To allow our application to get notifications of slack events, we first create a Slack App with Event Subscriptions as described [here](https://github.com/slackapi/python-slack-events-api#--development-workflow) + +Then, we set `SENDGRID_API_KEY` _(which you can create on the Sendgrid dashboard)_ and `SLACK_VERIFICATION_TOKEN` _(which you can get in the App Credentials section of the Slack App)_ as environment variables. + +Once this is done, we can subscribe to [events on Slack](https://api.slack.com/events) and trigger emails when an event occurs. In the example below, we trigger an email to `test@example.com` whenever someone posts a message on Slack that has the word "_help_" in it. + +``` +from slackeventsapi import SlackEventAdapter +from slackclient import SlackClient +import os +import sendgrid +from sendgrid.helpers.mail import * + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +SLACK_VERIFICATION_TOKEN = os.environ["SLACK_VERIFICATION_TOKEN"] +slack_events_adapter = SlackEventAdapter(SLACK_VERIFICATION_TOKEN, "/slack/events") + +@slack_events_adapter.on("message") +def handle_message(event_data): + message = event_data["event"] + # If the incoming message contains "help", then send an email using SendGrid + if message.get("subtype") is None and "help" in message.get('text').lower(): + message = "Someone needs your help: \n\n %s" % message["text"] + r = send_email(message) + print(r) + + +def send_email(message): + from_email = Email("slack_integration@example.com") + to_email = Email("test@example.com") + subject = "Psst... Someone needs help!" + content = Content("text/plain", message) + mail = Mail(from_email, subject, to_email, content) + response = sg.client.mail.send.post(request_body=mail.get()) + return response.status_code + +# Start the slack event listener server on port 3000 +slack_events_adapter.start(port=3000) +``` From b8b7f97c0a29211a27f95781d0ff00e5e8499fed Mon Sep 17 00:00:00 2001 From: heisendumb Date: Mon, 30 Oct 2017 00:26:08 -0200 Subject: [PATCH 14/45] docker-compose for issue #444 --- docker/Dockerfile | 4 +- docker/Makefile | 28 ++ docker/docker-compose.yml | 24 ++ .../examples/accesssettings/accesssettings.py | 84 ++++ docker/examples/alerts/alerts.py | 63 +++ docker/examples/apikeys/apikeys.py | 85 ++++ docker/examples/asm/asm.py | 174 ++++++++ docker/examples/browsers/browsers.py | 17 + docker/examples/campaigns/campaigns.py | 154 +++++++ docker/examples/categories/categories.py | 37 ++ docker/examples/clients/clients.py | 28 ++ docker/examples/contactdb/contactdb.py | 396 ++++++++++++++++++ docker/examples/devices/devices.py | 17 + docker/examples/geo/geo.py | 17 + docker/examples/helpers/mail/mail_example.py | 219 ++++++++++ docker/examples/ips/ips.py | 155 +++++++ docker/examples/mail/mail.py | 174 ++++++++ .../mailboxproviders/mailboxproviders.py | 17 + docker/examples/mailsettings/mailsettings.py | 220 ++++++++++ .../partnersettings/partnersettings.py | 40 ++ docker/examples/scopes/scopes.py | 16 + docker/examples/senders/senders.py | 99 +++++ docker/examples/stats/stats.py | 17 + docker/examples/subusers/subusers.py | 170 ++++++++ docker/examples/suppression/suppression.py | 202 +++++++++ .../trackingsettings/trackingsettings.py | 111 +++++ docker/examples/user/user.py | 294 +++++++++++++ docker/examples/whitelabel/whitelabel.py | 311 ++++++++++++++ 28 files changed, 3171 insertions(+), 2 deletions(-) create mode 100644 docker/Makefile create mode 100644 docker/docker-compose.yml create mode 100644 docker/examples/accesssettings/accesssettings.py create mode 100644 docker/examples/alerts/alerts.py create mode 100644 docker/examples/apikeys/apikeys.py create mode 100644 docker/examples/asm/asm.py create mode 100644 docker/examples/browsers/browsers.py create mode 100644 docker/examples/campaigns/campaigns.py create mode 100644 docker/examples/categories/categories.py create mode 100644 docker/examples/clients/clients.py create mode 100644 docker/examples/contactdb/contactdb.py create mode 100644 docker/examples/devices/devices.py create mode 100644 docker/examples/geo/geo.py create mode 100644 docker/examples/helpers/mail/mail_example.py create mode 100644 docker/examples/ips/ips.py create mode 100644 docker/examples/mail/mail.py create mode 100644 docker/examples/mailboxproviders/mailboxproviders.py create mode 100644 docker/examples/mailsettings/mailsettings.py create mode 100644 docker/examples/partnersettings/partnersettings.py create mode 100644 docker/examples/scopes/scopes.py create mode 100644 docker/examples/senders/senders.py create mode 100644 docker/examples/stats/stats.py create mode 100644 docker/examples/subusers/subusers.py create mode 100644 docker/examples/suppression/suppression.py create mode 100644 docker/examples/trackingsettings/trackingsettings.py create mode 100644 docker/examples/user/user.py create mode 100644 docker/examples/whitelabel/whitelabel.py diff --git a/docker/Dockerfile b/docker/Dockerfile index 798b494e0..448e07b03 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -36,8 +36,8 @@ RUN Python3.6 -m pip install flask # set up default sendgrid env WORKDIR /root/sources -RUN git clone https://github.com/sendgrid/sendgrid-python.git && \ - git clone https://github.com/sendgrid/python-http-client.git +RUN git clone https://github.com/sendgrid/sendgrid-python.git --branch && \ + git clone https://github.com/sendgrid/python-http-client.git --branch WORKDIR /root RUN ln -s /root/sources/sendgrid-python/sendgrid && \ ln -s /root/sources/python-http-client/python_http_client diff --git a/docker/Makefile b/docker/Makefile new file mode 100644 index 000000000..6ec47459d --- /dev/null +++ b/docker/Makefile @@ -0,0 +1,28 @@ +# import deploy config +deployfile=deploy.env +ifdef dpl +deployfile=$(dpl) +endif +include $(deployfile) +export $(shell sed 's/=.*//' $(deployfile)) + +stop: + docker-compose stop + +rm: stop + docker-compose stop -fvs + +clean: + docker rmi %(docker images -aq) + +clean_untagged: + docker rmi $(docker images --quiet --filter "dangling=true") 2>/dev/null + +build: + docker-compose up -d + +build-build: + docker-compose up --build -d + +up: rm clean build-build + echo "Sendgrid dev environment is alive :D" diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 000000000..d35772fd2 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,24 @@ +version: "3.3" + +services: + sendgrid: + image: sendgrid/sendgrid-python:${TAG} + restart: unless-stopped + container_name: sendgrid-prod + volumes: + - ${PATH_TO_SENDGRID-PYTHON_PROD}:/mnt/sendgrid-python + - ${PATH_TO_HTTP-CLIENT_PROD}:/mnt/python-http-client + env_file: .env + + sendgrid-dev: + build: + context: . + args: + - SENDGRID-PYTHON_VERSION: {SENDGRID-PYTHON_VERSION} + - HTTP-CLIENT_VERSION: {HTTP-CLIENT_VERSION} + restart: unless-stopped + container_name: sendgrid-dev + env_file: .env + volumes: + - ${PATH_TO_SENDGRID-PYTHON}:/mnt/sendgrid-python + - ${PATH_TO_HTTP-CLIENT}:/mnt/python-http-client diff --git a/docker/examples/accesssettings/accesssettings.py b/docker/examples/accesssettings/accesssettings.py new file mode 100644 index 000000000..aac0e4a54 --- /dev/null +++ b/docker/examples/accesssettings/accesssettings.py @@ -0,0 +1,84 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve all recent access attempts # +# GET /access_settings/activity # + +params = {'limit': 1} +response = sg.client.access_settings.activity.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add one or more IPs to the whitelist # +# POST /access_settings/whitelist # + +data = { + "ips": [ + { + "ip": "192.168.1.1" + }, + { + "ip": "192.*.*.*" + }, + { + "ip": "192.168.1.3/32" + } + ] +} +response = sg.client.access_settings.whitelist.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a list of currently whitelisted IPs # +# GET /access_settings/whitelist # + +response = sg.client.access_settings.whitelist.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Remove one or more IPs from the whitelist # +# DELETE /access_settings/whitelist # + +data = { + "ids": [ + 1, + 2, + 3 + ] +} +response = sg.client.access_settings.whitelist.delete(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a specific whitelisted IP # +# GET /access_settings/whitelist/{rule_id} # + +rule_id = "test_url_param" +response = sg.client.access_settings.whitelist._(rule_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Remove a specific IP from the whitelist # +# DELETE /access_settings/whitelist/{rule_id} # + +rule_id = "test_url_param" +response = sg.client.access_settings.whitelist._(rule_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/alerts/alerts.py b/docker/examples/alerts/alerts.py new file mode 100644 index 000000000..e30d48748 --- /dev/null +++ b/docker/examples/alerts/alerts.py @@ -0,0 +1,63 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create a new Alert # +# POST /alerts # + +data = { + "email_to": "example@example.com", + "frequency": "daily", + "type": "stats_notification" +} +response = sg.client.alerts.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all alerts # +# GET /alerts # + +response = sg.client.alerts.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update an alert # +# PATCH /alerts/{alert_id} # + +data = { + "email_to": "example@example.com" +} +alert_id = "test_url_param" +response = sg.client.alerts._(alert_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a specific alert # +# GET /alerts/{alert_id} # + +alert_id = "test_url_param" +response = sg.client.alerts._(alert_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete an alert # +# DELETE /alerts/{alert_id} # + +alert_id = "test_url_param" +response = sg.client.alerts._(alert_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/apikeys/apikeys.py b/docker/examples/apikeys/apikeys.py new file mode 100644 index 000000000..42c3afa10 --- /dev/null +++ b/docker/examples/apikeys/apikeys.py @@ -0,0 +1,85 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create API keys # +# POST /api_keys # + +data = { + "name": "My API Key", + "sample": "data", + "scopes": [ + "mail.send", + "alerts.create", + "alerts.read" + ] +} +response = sg.client.api_keys.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all API Keys belonging to the authenticated user # +# GET /api_keys # + +params = {'limit': 1} +response = sg.client.api_keys.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update the name & scopes of an API Key # +# PUT /api_keys/{api_key_id} # + +data = { + "name": "A New Hope", + "scopes": [ + "user.profile.read", + "user.profile.update" + ] +} +api_key_id = "test_url_param" +response = sg.client.api_keys._(api_key_id).put(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update API keys # +# PATCH /api_keys/{api_key_id} # + +data = { + "name": "A New Hope" +} +api_key_id = "test_url_param" +response = sg.client.api_keys._(api_key_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve an existing API Key # +# GET /api_keys/{api_key_id} # + +api_key_id = "test_url_param" +response = sg.client.api_keys._(api_key_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete API keys # +# DELETE /api_keys/{api_key_id} # + +api_key_id = "test_url_param" +response = sg.client.api_keys._(api_key_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/asm/asm.py b/docker/examples/asm/asm.py new file mode 100644 index 000000000..43130cf06 --- /dev/null +++ b/docker/examples/asm/asm.py @@ -0,0 +1,174 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create a new suppression group # +# POST /asm/groups # + +data = { + "description": "Suggestions for products our users might like.", + "is_default": True, + "name": "Product Suggestions" +} +response = sg.client.asm.groups.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve information about multiple suppression groups # +# GET /asm/groups # + +params = {'id': 1} +response = sg.client.asm.groups.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a suppression group. # +# PATCH /asm/groups/{group_id} # + +data = { + "description": "Suggestions for items our users might like.", + "id": 103, + "name": "Item Suggestions" +} +group_id = "test_url_param" +response = sg.client.asm.groups._(group_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Get information on a single suppression group. # +# GET /asm/groups/{group_id} # + +group_id = "test_url_param" +response = sg.client.asm.groups._(group_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a suppression group. # +# DELETE /asm/groups/{group_id} # + +group_id = "test_url_param" +response = sg.client.asm.groups._(group_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add suppressions to a suppression group # +# POST /asm/groups/{group_id}/suppressions # + +data = { + "recipient_emails": [ + "test1@example.com", + "test2@example.com" + ] +} +group_id = "test_url_param" +response = sg.client.asm.groups._(group_id).suppressions.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all suppressions for a suppression group # +# GET /asm/groups/{group_id}/suppressions # + +group_id = "test_url_param" +response = sg.client.asm.groups._(group_id).suppressions.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Search for suppressions within a group # +# POST /asm/groups/{group_id}/suppressions/search # + +data = { + "recipient_emails": [ + "exists1@example.com", + "exists2@example.com", + "doesnotexists@example.com" + ] +} +group_id = "test_url_param" +response = sg.client.asm.groups._(group_id).suppressions.search.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a suppression from a suppression group # +# DELETE /asm/groups/{group_id}/suppressions/{email} # + +group_id = "test_url_param" +email = "test_url_param" +response = sg.client.asm.groups._(group_id).suppressions._(email).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all suppressions # +# GET /asm/suppressions # + +response = sg.client.asm.suppressions.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add recipient addresses to the global suppression group. # +# POST /asm/suppressions/global # + +data = { + "recipient_emails": [ + "test1@example.com", + "test2@example.com" + ] +} +response = sg.client.asm.suppressions._("global").post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a Global Suppression # +# GET /asm/suppressions/global/{email} # + +email = "test_url_param" +response = sg.client.asm.suppressions._("global")._(email).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a Global Suppression # +# DELETE /asm/suppressions/global/{email} # + +email = "test_url_param" +response = sg.client.asm.suppressions._("global")._(email).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all suppression groups for an email address # +# GET /asm/suppressions/{email} # + +email = "test_url_param" +response = sg.client.asm.suppressions._(email).get() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/browsers/browsers.py b/docker/examples/browsers/browsers.py new file mode 100644 index 000000000..c123c12e5 --- /dev/null +++ b/docker/examples/browsers/browsers.py @@ -0,0 +1,17 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve email statistics by browser. # +# GET /browsers/stats # + +params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'browsers': 'test_string', 'limit': 'test_string', 'offset': 'test_string', 'start_date': '2016-01-01'} +response = sg.client.browsers.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/campaigns/campaigns.py b/docker/examples/campaigns/campaigns.py new file mode 100644 index 000000000..c77fc878b --- /dev/null +++ b/docker/examples/campaigns/campaigns.py @@ -0,0 +1,154 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create a Campaign # +# POST /campaigns # + +data = { + "categories": [ + "spring line" + ], + "custom_unsubscribe_url": "", + "html_content": "

Check out our spring line!

", + "ip_pool": "marketing", + "list_ids": [ + 110, + 124 + ], + "plain_content": "Check out our spring line!", + "segment_ids": [ + 110 + ], + "sender_id": 124451, + "subject": "New Products for Spring!", + "suppression_group_id": 42, + "title": "March Newsletter" +} +response = sg.client.campaigns.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all Campaigns # +# GET /campaigns # + +params = {'limit': 1, 'offset': 1} +response = sg.client.campaigns.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a Campaign # +# PATCH /campaigns/{campaign_id} # + +data = { + "categories": [ + "summer line" + ], + "html_content": "

Check out our summer line!

", + "plain_content": "Check out our summer line!", + "subject": "New Products for Summer!", + "title": "May Newsletter" +} +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a single campaign # +# GET /campaigns/{campaign_id} # + +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a Campaign # +# DELETE /campaigns/{campaign_id} # + +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a Scheduled Campaign # +# PATCH /campaigns/{campaign_id}/schedules # + +data = { + "send_at": 1489451436 +} +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).schedules.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Schedule a Campaign # +# POST /campaigns/{campaign_id}/schedules # + +data = { + "send_at": 1489771528 +} +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).schedules.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# View Scheduled Time of a Campaign # +# GET /campaigns/{campaign_id}/schedules # + +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).schedules.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Unschedule a Scheduled Campaign # +# DELETE /campaigns/{campaign_id}/schedules # + +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).schedules.delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Send a Campaign # +# POST /campaigns/{campaign_id}/schedules/now # + +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).schedules.now.post() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Send a Test Campaign # +# POST /campaigns/{campaign_id}/schedules/test # + +data = { + "to": "your.email@example.com" +} +campaign_id = "test_url_param" +response = sg.client.campaigns._(campaign_id).schedules.test.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/categories/categories.py b/docker/examples/categories/categories.py new file mode 100644 index 000000000..7984f0fe0 --- /dev/null +++ b/docker/examples/categories/categories.py @@ -0,0 +1,37 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve all categories # +# GET /categories # + +params = {'category': 'test_string', 'limit': 1, 'offset': 1} +response = sg.client.categories.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve Email Statistics for Categories # +# GET /categories/stats # + +params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01', 'categories': 'test_string'} +response = sg.client.categories.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve sums of email stats for each category [Needs: Stats object defined, has category ID?] # +# GET /categories/stats/sums # + +params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'limit': 1, 'sort_by_metric': 'test_string', 'offset': 1, 'start_date': '2016-01-01', 'sort_by_direction': 'asc'} +response = sg.client.categories.stats.sums.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/clients/clients.py b/docker/examples/clients/clients.py new file mode 100644 index 000000000..7831ef78f --- /dev/null +++ b/docker/examples/clients/clients.py @@ -0,0 +1,28 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve email statistics by client type. # +# GET /clients/stats # + +params = {'aggregated_by': 'day', 'start_date': '2016-01-01', 'end_date': '2016-04-01'} +response = sg.client.clients.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve stats by a specific client type. # +# GET /clients/{client_type}/stats # + +params = {'aggregated_by': 'day', 'start_date': '2016-01-01', 'end_date': '2016-04-01'} +client_type = "test_url_param" +response = sg.client.clients._(client_type).stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/contactdb/contactdb.py b/docker/examples/contactdb/contactdb.py new file mode 100644 index 000000000..c234d7724 --- /dev/null +++ b/docker/examples/contactdb/contactdb.py @@ -0,0 +1,396 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create a Custom Field # +# POST /contactdb/custom_fields # + +data = { + "name": "pet", + "type": "text" +} +response = sg.client.contactdb.custom_fields.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all custom fields # +# GET /contactdb/custom_fields # + +response = sg.client.contactdb.custom_fields.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a Custom Field # +# GET /contactdb/custom_fields/{custom_field_id} # + +custom_field_id = "test_url_param" +response = sg.client.contactdb.custom_fields._(custom_field_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a Custom Field # +# DELETE /contactdb/custom_fields/{custom_field_id} # + +custom_field_id = "test_url_param" +response = sg.client.contactdb.custom_fields._(custom_field_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Create a List # +# POST /contactdb/lists # + +data = { + "name": "your list name" +} +response = sg.client.contactdb.lists.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all lists # +# GET /contactdb/lists # + +response = sg.client.contactdb.lists.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete Multiple lists # +# DELETE /contactdb/lists # + +data = [ + 1, + 2, + 3, + 4 +] +response = sg.client.contactdb.lists.delete(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a List # +# PATCH /contactdb/lists/{list_id} # + +data = { + "name": "newlistname" +} +params = {'list_id': 1} +list_id = "test_url_param" +response = sg.client.contactdb.lists._(list_id).patch(request_body=data, query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a single list # +# GET /contactdb/lists/{list_id} # + +params = {'list_id': 1} +list_id = "test_url_param" +response = sg.client.contactdb.lists._(list_id).get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a List # +# DELETE /contactdb/lists/{list_id} # + +params = {'delete_contacts': 'true'} +list_id = "test_url_param" +response = sg.client.contactdb.lists._(list_id).delete(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add Multiple Recipients to a List # +# POST /contactdb/lists/{list_id}/recipients # + +data = [ + "recipient_id1", + "recipient_id2" +] +list_id = "test_url_param" +response = sg.client.contactdb.lists._(list_id).recipients.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all recipients on a List # +# GET /contactdb/lists/{list_id}/recipients # + +params = {'page': 1, 'page_size': 1} +list_id = "test_url_param" +response = sg.client.contactdb.lists._(list_id).recipients.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add a Single Recipient to a List # +# POST /contactdb/lists/{list_id}/recipients/{recipient_id} # + +list_id = "test_url_param" +recipient_id = "test_url_param" +response = sg.client.contactdb.lists._(list_id).recipients._(recipient_id).post() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a Single Recipient from a Single List # +# DELETE /contactdb/lists/{list_id}/recipients/{recipient_id} # + +params = {'recipient_id': 1, 'list_id': 1} +list_id = "test_url_param" +recipient_id = "test_url_param" +response = sg.client.contactdb.lists._(list_id).recipients._(recipient_id).delete(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update Recipient # +# PATCH /contactdb/recipients # + +data = [ + { + "email": "jones@example.com", + "first_name": "Guy", + "last_name": "Jones" + } +] +response = sg.client.contactdb.recipients.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add recipients # +# POST /contactdb/recipients # + +data = [ + { + "age": 25, + "email": "example@example.com", + "first_name": "", + "last_name": "User" + }, + { + "age": 25, + "email": "example2@example.com", + "first_name": "Example", + "last_name": "User" + } +] +response = sg.client.contactdb.recipients.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve recipients # +# GET /contactdb/recipients # + +params = {'page': 1, 'page_size': 1} +response = sg.client.contactdb.recipients.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete Recipient # +# DELETE /contactdb/recipients # + +data = [ + "recipient_id1", + "recipient_id2" +] +response = sg.client.contactdb.recipients.delete(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve the count of billable recipients # +# GET /contactdb/recipients/billable_count # + +response = sg.client.contactdb.recipients.billable_count.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a Count of Recipients # +# GET /contactdb/recipients/count # + +response = sg.client.contactdb.recipients.count.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve recipients matching search criteria # +# GET /contactdb/recipients/search # + +params = {'{field_name}': 'test_string'} +response = sg.client.contactdb.recipients.search.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a single recipient # +# GET /contactdb/recipients/{recipient_id} # + +recipient_id = "test_url_param" +response = sg.client.contactdb.recipients._(recipient_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a Recipient # +# DELETE /contactdb/recipients/{recipient_id} # + +recipient_id = "test_url_param" +response = sg.client.contactdb.recipients._(recipient_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve the lists that a recipient is on # +# GET /contactdb/recipients/{recipient_id}/lists # + +recipient_id = "test_url_param" +response = sg.client.contactdb.recipients._(recipient_id).lists.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve reserved fields # +# GET /contactdb/reserved_fields # + +response = sg.client.contactdb.reserved_fields.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Create a Segment # +# POST /contactdb/segments # + +data = { + "conditions": [ + { + "and_or": "", + "field": "last_name", + "operator": "eq", + "value": "Miller" + }, + { + "and_or": "and", + "field": "last_clicked", + "operator": "gt", + "value": "01/02/2015" + }, + { + "and_or": "or", + "field": "clicks.campaign_identifier", + "operator": "eq", + "value": "513" + } + ], + "list_id": 4, + "name": "Last Name Miller" +} +response = sg.client.contactdb.segments.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all segments # +# GET /contactdb/segments # + +response = sg.client.contactdb.segments.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a segment # +# PATCH /contactdb/segments/{segment_id} # + +data = { + "conditions": [ + { + "and_or": "", + "field": "last_name", + "operator": "eq", + "value": "Miller" + } + ], + "list_id": 5, + "name": "The Millers" +} +params = {'segment_id': 'test_string'} +segment_id = "test_url_param" +response = sg.client.contactdb.segments._(segment_id).patch(request_body=data, query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a segment # +# GET /contactdb/segments/{segment_id} # + +params = {'segment_id': 1} +segment_id = "test_url_param" +response = sg.client.contactdb.segments._(segment_id).get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a segment # +# DELETE /contactdb/segments/{segment_id} # + +params = {'delete_contacts': 'true'} +segment_id = "test_url_param" +response = sg.client.contactdb.segments._(segment_id).delete(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve recipients on a segment # +# GET /contactdb/segments/{segment_id}/recipients # + +params = {'page': 1, 'page_size': 1} +segment_id = "test_url_param" +response = sg.client.contactdb.segments._(segment_id).recipients.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/devices/devices.py b/docker/examples/devices/devices.py new file mode 100644 index 000000000..108e98452 --- /dev/null +++ b/docker/examples/devices/devices.py @@ -0,0 +1,17 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve email statistics by device type. # +# GET /devices/stats # + +params = {'aggregated_by': 'day', 'limit': 1, 'start_date': '2016-01-01', 'end_date': '2016-04-01', 'offset': 1} +response = sg.client.devices.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/geo/geo.py b/docker/examples/geo/geo.py new file mode 100644 index 000000000..7d58ec085 --- /dev/null +++ b/docker/examples/geo/geo.py @@ -0,0 +1,17 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve email statistics by country and state/province. # +# GET /geo/stats # + +params = {'end_date': '2016-04-01', 'country': 'US', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01'} +response = sg.client.geo.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/helpers/mail/mail_example.py b/docker/examples/helpers/mail/mail_example.py new file mode 100644 index 000000000..bfd8ea718 --- /dev/null +++ b/docker/examples/helpers/mail/mail_example.py @@ -0,0 +1,219 @@ +import json +import os +import urllib2 +from sendgrid.helpers.mail import * +from sendgrid import * + +# NOTE: you will need move this file to the root +# directory of this project to execute properly. + + +def build_hello_email(): + """Minimum required to send an email""" + from_email = Email("test@example.com") + subject = "Hello World from the SendGrid Python Library" + to_email = Email("test@example.com") + content = Content("text/plain", "some text here") + mail = Mail(from_email, subject, to_email, content) + mail.personalizations[0].add_to(Email("test2@example.com")) + + return mail.get() + + +def build_personalization(personalization): + """Build personalization mock instance from a mock dict""" + mock_personalization = Personalization() + for to_addr in personalization['to_list']: + personalization.add_to(to_addr) + + for cc_addr in personalization['cc_list']: + personalization.add_to(cc_addr) + + for bcc_addr in personalization['bcc_list']: + personalization.add_bc(bcc_addr) + + for header in personalization['headers']: + personalization.add_header(header) + + for substitution in personalization['substitutions']: + personalization.add_substitution(substitution) + + for arg in personalization['custom_args']: + personalization.add_custom_arg(arg) + + personalization.subject = personalization['subject'] + personalization.send_at = personalization['send_at'] + return mock_personalization + + +def get_mock_personalization_dict(): + """Get a dict of personalization mock.""" + mock_pers = dict() + + mock_pers['to_list'] = [Email("test1@example.com", + "Example User"), + Email("test2@example.com", + "Example User")] + + mock_pers['cc_list'] = [Email("test3@example.com", + "Example User"), + Email("test4@example.com", + "Example User")] + + mock_pers['bcc_list'] = [Email("test5@example.com"), + Email("test6@example.com")] + + mock_pers['subject'] = ("Hello World from the Personalized " + "SendGrid Python Library") + + mock_pers['headers'] = [Header("X-Test", "test"), + Header("X-Mock", "true")] + + mock_pers['substitutions'] = [Substitution("%name%", "Example User"), + Substitution("%city%", "Denver")] + + mock_pers['custom_args'] = [CustomArg("user_id", "343"), + CustomArg("type", "marketing")] + + mock_pers['send_at'] = 1443636843 + return mock_pers + + +def build_attachment1(): + """Build attachment mock.""" + attachment = Attachment() + attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl" + "Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12") + attachment.type = "application/pdf" + attachment.filename = "balance_001.pdf" + attachment.disposition = "attachment" + attachment.content_id = "Balance Sheet" + return attachment + + +def build_attachment2(): + """Build attachment mock.""" + attachment = Attachment() + attachment.content = "BwdW" + attachment.type = "image/png" + attachment.filename = "banner.png" + attachment.disposition = "inline" + attachment.content_id = "Banner" + return attachment + + +def build_mail_settings(): + """Build mail settings mock.""" + mail_settings = MailSettings() + mail_settings.bcc_settings = BCCSettings(True, Email("test@example.com")) + mail_settings.bypass_list_management = BypassListManagement(True) + mail_settings.footer_settings = FooterSettings(True, "Footer Text", + ("Footer " + "Text")) + mail_settings.sandbox_mode = SandBoxMode(True) + mail_settings.spam_check = SpamCheck(True, 1, + "https://spamcatcher.sendgrid.com") + return mail_settings + + +def build_tracking_settings(): + """Build tracking settings mock.""" + tracking_settings = TrackingSettings() + tracking_settings.click_tracking = ClickTracking(True, True) + tracking_settings.open_tracking = OpenTracking(True, + ("Optional tag to " + "replace with the" + "open image in the " + "body of the message")) + + subs_track = SubscriptionTracking(True, + ("text to insert into the " + "text/plain portion of the" + " message"), + ("html to insert " + "into the text/html portion of " + "the message"), + ("Optional tag to replace with " + "the open image in the body of " + "the message")) + + tracking_settings.subscription_tracking = subs_track + tracking_settings.ganalytics = Ganalytics(True, "some source", + "some medium", "some term", + "some_content", "some_campaign") + return tracking_settings + + +def build_kitchen_sink(): + """All settings set""" + mail = Mail() + + mail.from_email = Email("test@example.com", "Example User") + mail.subject = "Hello World from the SendGrid Python Library" + + personalization = get_mock_personalization_dict() + mail.add_personalization(build_personalization(personalization)) + mail.add_personalization(build_personalization(personalization)) + + mail.add_content(Content("text/plain", "some text here")) + mail.add_content(Content("text/html", ("some text " + "here"))) + + mail.add_attachment(build_attachment1()) + mail.add_attachment(build_attachment2()) + + mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932" + + mail.add_section(Section("%section1%", "Substitution Text for Section 1")) + mail.add_section(Section("%section2%", "Substitution Text for Section 2")) + + mail.add_header(Header("X-Test1", "test1")) + mail.add_header(Header("X-Test3", "test2")) + + mail.add_category(Category("May")) + mail.add_category(Category("2016")) + + mail.add_custom_arg(CustomArg("campaign", "welcome")) + mail.add_custom_arg(CustomArg("weekday", "morning")) + + mail.send_at = 1443636842 + + # This must be a valid [batch ID] + # (https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) to work + # mail.set_batch_id("N2VkYjBjYWItMGU4OC0xMWU2LWJhMzYtZjQ1Yzg5OTBkNzkxLWM5ZTUyZjNhOA") + mail.asm = ASM(99, [4, 5, 6, 7, 8]) + mail.ip_pool_name = "24" + mail.mail_settings = build_mail_settings() + mail.tracking_settings = build_tracking_settings() + mail.reply_to = Email("test@example.com") + + return mail.get() + + +def send_hello_email(): + # Assumes you set your environment variable: + # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key + sg = SendGridAPIClient() + data = build_hello_email() + response = sg.client.mail.send.post(request_body=data) + print(response.status_code) + print(response.headers) + print(response.body) + + +def send_kitchen_sink(): + # Assumes you set your environment variable: + # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key + sg = SendGridAPIClient() + data = build_kitchen_sink() + response = sg.client.mail.send.post(request_body=data) + print(response.status_code) + print(response.headers) + print(response.body) + + +# this will actually send an email +send_hello_email() + +# this will only send an email if you set SandBox Mode to False +send_kitchen_sink() diff --git a/docker/examples/ips/ips.py b/docker/examples/ips/ips.py new file mode 100644 index 000000000..6c48ae306 --- /dev/null +++ b/docker/examples/ips/ips.py @@ -0,0 +1,155 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve all IP addresses # +# GET /ips # + +params = {'subuser': 'test_string', 'ip': 'test_string', 'limit': 1, 'exclude_whitelabels': 'true', 'offset': 1} +response = sg.client.ips.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all assigned IPs # +# GET /ips/assigned # + +response = sg.client.ips.assigned.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Create an IP pool. # +# POST /ips/pools # + +data = { + "name": "marketing" +} +response = sg.client.ips.pools.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all IP pools. # +# GET /ips/pools # + +response = sg.client.ips.pools.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update an IP pools name. # +# PUT /ips/pools/{pool_name} # + +data = { + "name": "new_pool_name" +} +pool_name = "test_url_param" +response = sg.client.ips.pools._(pool_name).put(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all IPs in a specified pool. # +# GET /ips/pools/{pool_name} # + +pool_name = "test_url_param" +response = sg.client.ips.pools._(pool_name).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete an IP pool. # +# DELETE /ips/pools/{pool_name} # + +pool_name = "test_url_param" +response = sg.client.ips.pools._(pool_name).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add an IP address to a pool # +# POST /ips/pools/{pool_name}/ips # + +data = { + "ip": "0.0.0.0" +} +pool_name = "test_url_param" +response = sg.client.ips.pools._(pool_name).ips.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Remove an IP address from a pool. # +# DELETE /ips/pools/{pool_name}/ips/{ip} # + +pool_name = "test_url_param" +ip = "test_url_param" +response = sg.client.ips.pools._(pool_name).ips._(ip).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add an IP to warmup # +# POST /ips/warmup # + +data = { + "ip": "0.0.0.0" +} +response = sg.client.ips.warmup.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all IPs currently in warmup # +# GET /ips/warmup # + +response = sg.client.ips.warmup.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve warmup status for a specific IP address # +# GET /ips/warmup/{ip_address} # + +ip_address = "test_url_param" +response = sg.client.ips.warmup._(ip_address).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Remove an IP from warmup # +# DELETE /ips/warmup/{ip_address} # + +ip_address = "test_url_param" +response = sg.client.ips.warmup._(ip_address).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all IP pools an IP address belongs to # +# GET /ips/{ip_address} # + +ip_address = "test_url_param" +response = sg.client.ips._(ip_address).get() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/mail/mail.py b/docker/examples/mail/mail.py new file mode 100644 index 000000000..fef420e87 --- /dev/null +++ b/docker/examples/mail/mail.py @@ -0,0 +1,174 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create a batch ID # +# POST /mail/batch # + +response = sg.client.mail.batch.post() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Validate batch ID # +# GET /mail/batch/{batch_id} # + +batch_id = "test_url_param" +response = sg.client.mail.batch._(batch_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# v3 Mail Send # +# POST /mail/send # +# This endpoint has a helper, check it out [here](https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/helpers/mail/README.md). + +data = { + "asm": { + "group_id": 1, + "groups_to_display": [ + 1, + 2, + 3 + ] + }, + "attachments": [ + { + "content": "[BASE64 encoded content block here]", + "content_id": "ii_139db99fdb5c3704", + "disposition": "inline", + "filename": "file1.jpg", + "name": "file1", + "type": "jpg" + } + ], + "batch_id": "[YOUR BATCH ID GOES HERE]", + "categories": [ + "category1", + "category2" + ], + "content": [ + { + "type": "text/html", + "value": "

Hello, world!

" + } + ], + "custom_args": { + "New Argument 1": "New Value 1", + "activationAttempt": "1", + "customerAccountNumber": "[CUSTOMER ACCOUNT NUMBER GOES HERE]" + }, + "from": { + "email": "sam.smith@example.com", + "name": "Sam Smith" + }, + "headers": {}, + "ip_pool_name": "[YOUR POOL NAME GOES HERE]", + "mail_settings": { + "bcc": { + "email": "ben.doe@example.com", + "enable": True + }, + "bypass_list_management": { + "enable": True + }, + "footer": { + "enable": True, + "html": "

Thanks
The SendGrid Team

", + "text": "Thanks,/n The SendGrid Team" + }, + "sandbox_mode": { + "enable": False + }, + "spam_check": { + "enable": True, + "post_to_url": "http://example.com/compliance", + "threshold": 3 + } + }, + "personalizations": [ + { + "bcc": [ + { + "email": "sam.doe@example.com", + "name": "Sam Doe" + } + ], + "cc": [ + { + "email": "jane.doe@example.com", + "name": "Jane Doe" + } + ], + "custom_args": { + "New Argument 1": "New Value 1", + "activationAttempt": "1", + "customerAccountNumber": "[CUSTOMER ACCOUNT NUMBER GOES HERE]" + }, + "headers": { + "X-Accept-Language": "en", + "X-Mailer": "MyApp" + }, + "send_at": 1409348513, + "subject": "Hello, World!", + "substitutions": { + "id": "substitutions", + "type": "object" + }, + "to": [ + { + "email": "john.doe@example.com", + "name": "John Doe" + } + ] + } + ], + "reply_to": { + "email": "sam.smith@example.com", + "name": "Sam Smith" + }, + "sections": { + "section": { + ":sectionName1": "section 1 text", + ":sectionName2": "section 2 text" + } + }, + "send_at": 1409348513, + "subject": "Hello, World!", + "template_id": "[YOUR TEMPLATE ID GOES HERE]", + "tracking_settings": { + "click_tracking": { + "enable": True, + "enable_text": True + }, + "ganalytics": { + "enable": True, + "utm_campaign": "[NAME OF YOUR REFERRER SOURCE]", + "utm_content": "[USE THIS SPACE TO DIFFERENTIATE YOUR EMAIL FROM ADS]", + "utm_medium": "[NAME OF YOUR MARKETING MEDIUM e.g. email]", + "utm_name": "[NAME OF YOUR CAMPAIGN]", + "utm_term": "[IDENTIFY PAID KEYWORDS HERE]" + }, + "open_tracking": { + "enable": True, + "substitution_tag": "%opentrack" + }, + "subscription_tracking": { + "enable": True, + "html": "If you would like to unsubscribe and stop receiving these emails <% clickhere %>.", + "substitution_tag": "<%click here%>", + "text": "If you would like to unsubscribe and stop receiveing these emails <% click here %>." + } + } +} +response = sg.client.mail.send.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/mailboxproviders/mailboxproviders.py b/docker/examples/mailboxproviders/mailboxproviders.py new file mode 100644 index 000000000..1b75ecac5 --- /dev/null +++ b/docker/examples/mailboxproviders/mailboxproviders.py @@ -0,0 +1,17 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve email statistics by mailbox provider. # +# GET /mailbox_providers/stats # + +params = {'end_date': '2016-04-01', 'mailbox_providers': 'test_string', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01'} +response = sg.client.mailbox_providers.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/mailsettings/mailsettings.py b/docker/examples/mailsettings/mailsettings.py new file mode 100644 index 000000000..18c57b960 --- /dev/null +++ b/docker/examples/mailsettings/mailsettings.py @@ -0,0 +1,220 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve all mail settings # +# GET /mail_settings # + +params = {'limit': 1, 'offset': 1} +response = sg.client.mail_settings.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update address whitelist mail settings # +# PATCH /mail_settings/address_whitelist # + +data = { + "enabled": True, + "list": [ + "email1@example.com", + "example.com" + ] +} +response = sg.client.mail_settings.address_whitelist.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve address whitelist mail settings # +# GET /mail_settings/address_whitelist # + +response = sg.client.mail_settings.address_whitelist.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update BCC mail settings # +# PATCH /mail_settings/bcc # + +data = { + "email": "email@example.com", + "enabled": False +} +response = sg.client.mail_settings.bcc.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all BCC mail settings # +# GET /mail_settings/bcc # + +response = sg.client.mail_settings.bcc.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update bounce purge mail settings # +# PATCH /mail_settings/bounce_purge # + +data = { + "enabled": True, + "hard_bounces": 5, + "soft_bounces": 5 +} +response = sg.client.mail_settings.bounce_purge.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve bounce purge mail settings # +# GET /mail_settings/bounce_purge # + +response = sg.client.mail_settings.bounce_purge.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update footer mail settings # +# PATCH /mail_settings/footer # + +data = { + "enabled": True, + "html_content": "...", + "plain_content": "..." +} +response = sg.client.mail_settings.footer.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve footer mail settings # +# GET /mail_settings/footer # + +response = sg.client.mail_settings.footer.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update forward bounce mail settings # +# PATCH /mail_settings/forward_bounce # + +data = { + "email": "example@example.com", + "enabled": True +} +response = sg.client.mail_settings.forward_bounce.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve forward bounce mail settings # +# GET /mail_settings/forward_bounce # + +response = sg.client.mail_settings.forward_bounce.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update forward spam mail settings # +# PATCH /mail_settings/forward_spam # + +data = { + "email": "", + "enabled": False +} +response = sg.client.mail_settings.forward_spam.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve forward spam mail settings # +# GET /mail_settings/forward_spam # + +response = sg.client.mail_settings.forward_spam.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update plain content mail settings # +# PATCH /mail_settings/plain_content # + +data = { + "enabled": False +} +response = sg.client.mail_settings.plain_content.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve plain content mail settings # +# GET /mail_settings/plain_content # + +response = sg.client.mail_settings.plain_content.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update spam check mail settings # +# PATCH /mail_settings/spam_check # + +data = { + "enabled": True, + "max_score": 5, + "url": "url" +} +response = sg.client.mail_settings.spam_check.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve spam check mail settings # +# GET /mail_settings/spam_check # + +response = sg.client.mail_settings.spam_check.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update template mail settings # +# PATCH /mail_settings/template # + +data = { + "enabled": True, + "html_content": "<% body %>" +} +response = sg.client.mail_settings.template.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve legacy template mail settings # +# GET /mail_settings/template # + +response = sg.client.mail_settings.template.get() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/partnersettings/partnersettings.py b/docker/examples/partnersettings/partnersettings.py new file mode 100644 index 000000000..37f77f4e6 --- /dev/null +++ b/docker/examples/partnersettings/partnersettings.py @@ -0,0 +1,40 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Returns a list of all partner settings. # +# GET /partner_settings # + +params = {'limit': 1, 'offset': 1} +response = sg.client.partner_settings.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Updates New Relic partner settings. # +# PATCH /partner_settings/new_relic # + +data = { + "enable_subuser_statistics": True, + "enabled": True, + "license_key": "" +} +response = sg.client.partner_settings.new_relic.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Returns all New Relic partner settings. # +# GET /partner_settings/new_relic # + +response = sg.client.partner_settings.new_relic.get() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/scopes/scopes.py b/docker/examples/scopes/scopes.py new file mode 100644 index 000000000..124f77d39 --- /dev/null +++ b/docker/examples/scopes/scopes.py @@ -0,0 +1,16 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve a list of scopes for which this user has access. # +# GET /scopes # + +response = sg.client.scopes.get() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/senders/senders.py b/docker/examples/senders/senders.py new file mode 100644 index 000000000..f21459b71 --- /dev/null +++ b/docker/examples/senders/senders.py @@ -0,0 +1,99 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create a Sender Identity # +# POST /senders # + +data = { + "address": "123 Elm St.", + "address_2": "Apt. 456", + "city": "Denver", + "country": "United States", + "from": { + "email": "from@example.com", + "name": "Example INC" + }, + "nickname": "My Sender ID", + "reply_to": { + "email": "replyto@example.com", + "name": "Example INC" + }, + "state": "Colorado", + "zip": "80202" +} +response = sg.client.senders.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Get all Sender Identities # +# GET /senders # + +response = sg.client.senders.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a Sender Identity # +# PATCH /senders/{sender_id} # + +data = { + "address": "123 Elm St.", + "address_2": "Apt. 456", + "city": "Denver", + "country": "United States", + "from": { + "email": "from@example.com", + "name": "Example INC" + }, + "nickname": "My Sender ID", + "reply_to": { + "email": "replyto@example.com", + "name": "Example INC" + }, + "state": "Colorado", + "zip": "80202" +} +sender_id = "test_url_param" +response = sg.client.senders._(sender_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# View a Sender Identity # +# GET /senders/{sender_id} # + +sender_id = "test_url_param" +response = sg.client.senders._(sender_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a Sender Identity # +# DELETE /senders/{sender_id} # + +sender_id = "test_url_param" +response = sg.client.senders._(sender_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Resend Sender Identity Verification # +# POST /senders/{sender_id}/resend_verification # + +sender_id = "test_url_param" +response = sg.client.senders._(sender_id).resend_verification.post() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/stats/stats.py b/docker/examples/stats/stats.py new file mode 100644 index 000000000..a7bf3362e --- /dev/null +++ b/docker/examples/stats/stats.py @@ -0,0 +1,17 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve global email statistics # +# GET /stats # + +params = {'aggregated_by': 'day', 'limit': 1, 'start_date': '2016-01-01', 'end_date': '2016-04-01', 'offset': 1} +response = sg.client.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/subusers/subusers.py b/docker/examples/subusers/subusers.py new file mode 100644 index 000000000..6aa91e535 --- /dev/null +++ b/docker/examples/subusers/subusers.py @@ -0,0 +1,170 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create Subuser # +# POST /subusers # + +data = { + "email": "John@example.com", + "ips": [ + "1.1.1.1", + "2.2.2.2" + ], + "password": "johns_password", + "username": "John@example.com" +} +response = sg.client.subusers.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# List all Subusers # +# GET /subusers # + +params = {'username': 'test_string', 'limit': 1, 'offset': 1} +response = sg.client.subusers.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve Subuser Reputations # +# GET /subusers/reputations # + +params = {'usernames': 'test_string'} +response = sg.client.subusers.reputations.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve email statistics for your subusers. # +# GET /subusers/stats # + +params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01', 'subusers': 'test_string'} +response = sg.client.subusers.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve monthly stats for all subusers # +# GET /subusers/stats/monthly # + +params = {'subuser': 'test_string', 'limit': 1, 'sort_by_metric': 'test_string', 'offset': 1, 'date': 'test_string', 'sort_by_direction': 'asc'} +response = sg.client.subusers.stats.monthly.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve the totals for each email statistic metric for all subusers. # +# GET /subusers/stats/sums # + +params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'limit': 1, 'sort_by_metric': 'test_string', 'offset': 1, 'start_date': '2016-01-01', 'sort_by_direction': 'asc'} +response = sg.client.subusers.stats.sums.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Enable/disable a subuser # +# PATCH /subusers/{subuser_name} # + +data = { + "disabled": False +} +subuser_name = "test_url_param" +response = sg.client.subusers._(subuser_name).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a subuser # +# DELETE /subusers/{subuser_name} # + +subuser_name = "test_url_param" +response = sg.client.subusers._(subuser_name).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update IPs assigned to a subuser # +# PUT /subusers/{subuser_name}/ips # + +data = [ + "127.0.0.1" +] +subuser_name = "test_url_param" +response = sg.client.subusers._(subuser_name).ips.put(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update Monitor Settings for a subuser # +# PUT /subusers/{subuser_name}/monitor # + +data = { + "email": "example@example.com", + "frequency": 500 +} +subuser_name = "test_url_param" +response = sg.client.subusers._(subuser_name).monitor.put(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Create monitor settings # +# POST /subusers/{subuser_name}/monitor # + +data = { + "email": "example@example.com", + "frequency": 50000 +} +subuser_name = "test_url_param" +response = sg.client.subusers._(subuser_name).monitor.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve monitor settings for a subuser # +# GET /subusers/{subuser_name}/monitor # + +subuser_name = "test_url_param" +response = sg.client.subusers._(subuser_name).monitor.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete monitor settings # +# DELETE /subusers/{subuser_name}/monitor # + +subuser_name = "test_url_param" +response = sg.client.subusers._(subuser_name).monitor.delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve the monthly email statistics for a single subuser # +# GET /subusers/{subuser_name}/stats/monthly # + +params = {'date': 'test_string', 'sort_by_direction': 'asc', 'limit': 1, 'sort_by_metric': 'test_string', 'offset': 1} +subuser_name = "test_url_param" +response = sg.client.subusers._(subuser_name).stats.monthly.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/suppression/suppression.py b/docker/examples/suppression/suppression.py new file mode 100644 index 000000000..abdaef76d --- /dev/null +++ b/docker/examples/suppression/suppression.py @@ -0,0 +1,202 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve all blocks # +# GET /suppression/blocks # + +params = {'start_time': 1, 'limit': 1, 'end_time': 1, 'offset': 1} +response = sg.client.suppression.blocks.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete blocks # +# DELETE /suppression/blocks # + +data = { + "delete_all": False, + "emails": [ + "example1@example.com", + "example2@example.com" + ] +} +response = sg.client.suppression.blocks.delete(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a specific block # +# GET /suppression/blocks/{email} # + +email = "test_url_param" +response = sg.client.suppression.blocks._(email).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a specific block # +# DELETE /suppression/blocks/{email} # + +email = "test_url_param" +response = sg.client.suppression.blocks._(email).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all bounces # +# GET /suppression/bounces # + +params = {'start_time': 1, 'end_time': 1} +response = sg.client.suppression.bounces.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete bounces # +# DELETE /suppression/bounces # + +data = { + "delete_all": True, + "emails": [ + "example@example.com", + "example2@example.com" + ] +} +response = sg.client.suppression.bounces.delete(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a Bounce # +# GET /suppression/bounces/{email} # + +email = "test_url_param" +response = sg.client.suppression.bounces._(email).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a bounce # +# DELETE /suppression/bounces/{email} # + +params = {'email_address': 'example@example.com'} +email = "test_url_param" +response = sg.client.suppression.bounces._(email).delete(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all invalid emails # +# GET /suppression/invalid_emails # + +params = {'start_time': 1, 'limit': 1, 'end_time': 1, 'offset': 1} +response = sg.client.suppression.invalid_emails.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete invalid emails # +# DELETE /suppression/invalid_emails # + +data = { + "delete_all": False, + "emails": [ + "example1@example.com", + "example2@example.com" + ] +} +response = sg.client.suppression.invalid_emails.delete(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a specific invalid email # +# GET /suppression/invalid_emails/{email} # + +email = "test_url_param" +response = sg.client.suppression.invalid_emails._(email).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a specific invalid email # +# DELETE /suppression/invalid_emails/{email} # + +email = "test_url_param" +response = sg.client.suppression.invalid_emails._(email).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a specific spam report # +# GET /suppression/spam_report/{email} # + +email = "test_url_param" +response = sg.client.suppression.spam_report._(email).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a specific spam report # +# DELETE /suppression/spam_report/{email} # + +email = "test_url_param" +response = sg.client.suppression.spam_report._(email).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all spam reports # +# GET /suppression/spam_reports # + +params = {'start_time': 1, 'limit': 1, 'end_time': 1, 'offset': 1} +response = sg.client.suppression.spam_reports.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete spam reports # +# DELETE /suppression/spam_reports # + +data = { + "delete_all": False, + "emails": [ + "example1@example.com", + "example2@example.com" + ] +} +response = sg.client.suppression.spam_reports.delete(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all global suppressions # +# GET /suppression/unsubscribes # + +params = {'start_time': 1, 'limit': 1, 'end_time': 1, 'offset': 1} +response = sg.client.suppression.unsubscribes.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/trackingsettings/trackingsettings.py b/docker/examples/trackingsettings/trackingsettings.py new file mode 100644 index 000000000..80dbe243a --- /dev/null +++ b/docker/examples/trackingsettings/trackingsettings.py @@ -0,0 +1,111 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Retrieve Tracking Settings # +# GET /tracking_settings # + +params = {'limit': 1, 'offset': 1} +response = sg.client.tracking_settings.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update Click Tracking Settings # +# PATCH /tracking_settings/click # + +data = { + "enabled": True +} +response = sg.client.tracking_settings.click.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve Click Track Settings # +# GET /tracking_settings/click # + +response = sg.client.tracking_settings.click.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update Google Analytics Settings # +# PATCH /tracking_settings/google_analytics # + +data = { + "enabled": True, + "utm_campaign": "website", + "utm_content": "", + "utm_medium": "email", + "utm_source": "sendgrid.com", + "utm_term": "" +} +response = sg.client.tracking_settings.google_analytics.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve Google Analytics Settings # +# GET /tracking_settings/google_analytics # + +response = sg.client.tracking_settings.google_analytics.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update Open Tracking Settings # +# PATCH /tracking_settings/open # + +data = { + "enabled": True +} +response = sg.client.tracking_settings.open.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Get Open Tracking Settings # +# GET /tracking_settings/open # + +response = sg.client.tracking_settings.open.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update Subscription Tracking Settings # +# PATCH /tracking_settings/subscription # + +data = { + "enabled": True, + "html_content": "html content", + "landing": "landing page html", + "plain_content": "text content", + "replace": "replacement tag", + "url": "url" +} +response = sg.client.tracking_settings.subscription.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve Subscription Tracking Settings # +# GET /tracking_settings/subscription # + +response = sg.client.tracking_settings.subscription.get() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/user/user.py b/docker/examples/user/user.py new file mode 100644 index 000000000..9e3f24766 --- /dev/null +++ b/docker/examples/user/user.py @@ -0,0 +1,294 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Get a user's account information. # +# GET /user/account # + +response = sg.client.user.account.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve your credit balance # +# GET /user/credits # + +response = sg.client.user.credits.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update your account email address # +# PUT /user/email # + +data = { + "email": "example@example.com" +} +response = sg.client.user.email.put(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve your account email address # +# GET /user/email # + +response = sg.client.user.email.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update your password # +# PUT /user/password # + +data = { + "new_password": "new_password", + "old_password": "old_password" +} +response = sg.client.user.password.put(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a user's profile # +# PATCH /user/profile # + +data = { + "city": "Orange", + "first_name": "Example", + "last_name": "User" +} +response = sg.client.user.profile.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Get a user's profile # +# GET /user/profile # + +response = sg.client.user.profile.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Cancel or pause a scheduled send # +# POST /user/scheduled_sends # + +data = { + "batch_id": "YOUR_BATCH_ID", + "status": "pause" +} +response = sg.client.user.scheduled_sends.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all scheduled sends # +# GET /user/scheduled_sends # + +response = sg.client.user.scheduled_sends.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update user scheduled send information # +# PATCH /user/scheduled_sends/{batch_id} # + +data = { + "status": "pause" +} +batch_id = "test_url_param" +response = sg.client.user.scheduled_sends._(batch_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve scheduled send # +# GET /user/scheduled_sends/{batch_id} # + +batch_id = "test_url_param" +response = sg.client.user.scheduled_sends._(batch_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a cancellation or pause of a scheduled send # +# DELETE /user/scheduled_sends/{batch_id} # + +batch_id = "test_url_param" +response = sg.client.user.scheduled_sends._(batch_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update Enforced TLS settings # +# PATCH /user/settings/enforced_tls # + +data = { + "require_tls": True, + "require_valid_cert": False +} +response = sg.client.user.settings.enforced_tls.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve current Enforced TLS settings. # +# GET /user/settings/enforced_tls # + +response = sg.client.user.settings.enforced_tls.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update your username # +# PUT /user/username # + +data = { + "username": "test_username" +} +response = sg.client.user.username.put(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve your username # +# GET /user/username # + +response = sg.client.user.username.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update Event Notification Settings # +# PATCH /user/webhooks/event/settings # + +data = { + "bounce": True, + "click": True, + "deferred": True, + "delivered": True, + "dropped": True, + "enabled": True, + "group_resubscribe": True, + "group_unsubscribe": True, + "open": True, + "processed": True, + "spam_report": True, + "unsubscribe": True, + "url": "url" +} +response = sg.client.user.webhooks.event.settings.patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve Event Webhook settings # +# GET /user/webhooks/event/settings # + +response = sg.client.user.webhooks.event.settings.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Test Event Notification Settings # +# POST /user/webhooks/event/test # + +data = { + "url": "url" +} +response = sg.client.user.webhooks.event.test.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Create a parse setting # +# POST /user/webhooks/parse/settings # + +data = { + "hostname": "myhostname.com", + "send_raw": False, + "spam_check": True, + "url": "http://email.myhosthame.com" +} +response = sg.client.user.webhooks.parse.settings.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all parse settings # +# GET /user/webhooks/parse/settings # + +response = sg.client.user.webhooks.parse.settings.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a parse setting # +# PATCH /user/webhooks/parse/settings/{hostname} # + +data = { + "send_raw": True, + "spam_check": False, + "url": "http://newdomain.com/parse" +} +hostname = "test_url_param" +response = sg.client.user.webhooks.parse.settings._(hostname).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a specific parse setting # +# GET /user/webhooks/parse/settings/{hostname} # + +hostname = "test_url_param" +response = sg.client.user.webhooks.parse.settings._(hostname).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a parse setting # +# DELETE /user/webhooks/parse/settings/{hostname} # + +hostname = "test_url_param" +response = sg.client.user.webhooks.parse.settings._(hostname).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieves Inbound Parse Webhook statistics. # +# GET /user/webhooks/parse/stats # + +params = {'aggregated_by': 'day', 'limit': 'test_string', 'start_date': '2016-01-01', 'end_date': '2016-04-01', 'offset': 'test_string'} +response = sg.client.user.webhooks.parse.stats.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/examples/whitelabel/whitelabel.py b/docker/examples/whitelabel/whitelabel.py new file mode 100644 index 000000000..f529d3ed2 --- /dev/null +++ b/docker/examples/whitelabel/whitelabel.py @@ -0,0 +1,311 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create a domain whitelabel. # +# POST /whitelabel/domains # + +data = { + "automatic_security": False, + "custom_spf": True, + "default": True, + "domain": "example.com", + "ips": [ + "192.168.1.1", + "192.168.1.2" + ], + "subdomain": "news", + "username": "john@example.com" +} +response = sg.client.whitelabel.domains.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# List all domain whitelabels. # +# GET /whitelabel/domains # + +params = {'username': 'test_string', 'domain': 'test_string', 'exclude_subusers': 'true', 'limit': 1, 'offset': 1} +response = sg.client.whitelabel.domains.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Get the default domain whitelabel. # +# GET /whitelabel/domains/default # + +response = sg.client.whitelabel.domains.default.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# List the domain whitelabel associated with the given user. # +# GET /whitelabel/domains/subuser # + +response = sg.client.whitelabel.domains.subuser.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Disassociate a domain whitelabel from a given user. # +# DELETE /whitelabel/domains/subuser # + +response = sg.client.whitelabel.domains.subuser.delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a domain whitelabel. # +# PATCH /whitelabel/domains/{domain_id} # + +data = { + "custom_spf": True, + "default": False +} +domain_id = "test_url_param" +response = sg.client.whitelabel.domains._(domain_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a domain whitelabel. # +# GET /whitelabel/domains/{domain_id} # + +domain_id = "test_url_param" +response = sg.client.whitelabel.domains._(domain_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a domain whitelabel. # +# DELETE /whitelabel/domains/{domain_id} # + +domain_id = "test_url_param" +response = sg.client.whitelabel.domains._(domain_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Associate a domain whitelabel with a given user. # +# POST /whitelabel/domains/{domain_id}/subuser # + +data = { + "username": "jane@example.com" +} +domain_id = "test_url_param" +response = sg.client.whitelabel.domains._(domain_id).subuser.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Add an IP to a domain whitelabel. # +# POST /whitelabel/domains/{id}/ips # + +data = { + "ip": "192.168.0.1" +} +id = "test_url_param" +response = sg.client.whitelabel.domains._(id).ips.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Remove an IP from a domain whitelabel. # +# DELETE /whitelabel/domains/{id}/ips/{ip} # + +id = "test_url_param" +ip = "test_url_param" +response = sg.client.whitelabel.domains._(id).ips._(ip).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Validate a domain whitelabel. # +# POST /whitelabel/domains/{id}/validate # + +id = "test_url_param" +response = sg.client.whitelabel.domains._(id).validate.post() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Create an IP whitelabel # +# POST /whitelabel/ips # + +data = { + "domain": "example.com", + "ip": "192.168.1.1", + "subdomain": "email" +} +response = sg.client.whitelabel.ips.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all IP whitelabels # +# GET /whitelabel/ips # + +params = {'ip': 'test_string', 'limit': 1, 'offset': 1} +response = sg.client.whitelabel.ips.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve an IP whitelabel # +# GET /whitelabel/ips/{id} # + +id = "test_url_param" +response = sg.client.whitelabel.ips._(id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete an IP whitelabel # +# DELETE /whitelabel/ips/{id} # + +id = "test_url_param" +response = sg.client.whitelabel.ips._(id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Validate an IP whitelabel # +# POST /whitelabel/ips/{id}/validate # + +id = "test_url_param" +response = sg.client.whitelabel.ips._(id).validate.post() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Create a Link Whitelabel # +# POST /whitelabel/links # + +data = { + "default": True, + "domain": "example.com", + "subdomain": "mail" +} +params = {'limit': 1, 'offset': 1} +response = sg.client.whitelabel.links.post(request_body=data, query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all link whitelabels # +# GET /whitelabel/links # + +params = {'limit': 1} +response = sg.client.whitelabel.links.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a Default Link Whitelabel # +# GET /whitelabel/links/default # + +params = {'domain': 'test_string'} +response = sg.client.whitelabel.links.default.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve Associated Link Whitelabel # +# GET /whitelabel/links/subuser # + +params = {'username': 'test_string'} +response = sg.client.whitelabel.links.subuser.get(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Disassociate a Link Whitelabel # +# DELETE /whitelabel/links/subuser # + +params = {'username': 'test_string'} +response = sg.client.whitelabel.links.subuser.delete(query_params=params) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Update a Link Whitelabel # +# PATCH /whitelabel/links/{id} # + +data = { + "default": True +} +id = "test_url_param" +response = sg.client.whitelabel.links._(id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a Link Whitelabel # +# GET /whitelabel/links/{id} # + +id = "test_url_param" +response = sg.client.whitelabel.links._(id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a Link Whitelabel # +# DELETE /whitelabel/links/{id} # + +id = "test_url_param" +response = sg.client.whitelabel.links._(id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Validate a Link Whitelabel # +# POST /whitelabel/links/{id}/validate # + +id = "test_url_param" +response = sg.client.whitelabel.links._(id).validate.post() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Associate a Link Whitelabel # +# POST /whitelabel/links/{link_id}/subuser # + +data = { + "username": "jane@example.com" +} +link_id = "test_url_param" +response = sg.client.whitelabel.links._(link_id).subuser.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + From b82fda792ee0754a717a1ba95dd67a1032d27337 Mon Sep 17 00:00:00 2001 From: heisendumb Date: Mon, 30 Oct 2017 00:31:16 -0200 Subject: [PATCH 15/45] added args to Dockerfile --- docker/Dockerfile | 7 +++++-- docker/Makefile | 8 -------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 448e07b03..9de0928a1 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -2,6 +2,9 @@ FROM ubuntu:xenial ENV PYTHON_VERSIONS='python2.7 python3.4 python3.5 python3.6' \ OAI_SPEC_URL="https://raw.githubusercontent.com/sendgrid/sendgrid-oai/master/oai_stoplight.json" +ARG SENDGRID-PYTHON_VERSION +ARG BRANCH_HTTP_CLIENT + # install testing versions of python, including old versions, from deadsnakes RUN set -x \ && apt-get update \ @@ -36,8 +39,8 @@ RUN Python3.6 -m pip install flask # set up default sendgrid env WORKDIR /root/sources -RUN git clone https://github.com/sendgrid/sendgrid-python.git --branch && \ - git clone https://github.com/sendgrid/python-http-client.git --branch +RUN git clone https://github.com/sendgrid/sendgrid-python.git --branch $SENDGRID-PYTHON_VERSION && \ + git clone https://github.com/sendgrid/python-http-client.git --branch $HTTP-CLIENT_VERSION WORKDIR /root RUN ln -s /root/sources/sendgrid-python/sendgrid && \ ln -s /root/sources/python-http-client/python_http_client diff --git a/docker/Makefile b/docker/Makefile index 6ec47459d..1afc31189 100644 --- a/docker/Makefile +++ b/docker/Makefile @@ -1,11 +1,3 @@ -# import deploy config -deployfile=deploy.env -ifdef dpl -deployfile=$(dpl) -endif -include $(deployfile) -export $(shell sed 's/=.*//' $(deployfile)) - stop: docker-compose stop From 310648d9213c101b9c0997f077ae7bf8ed1bd014 Mon Sep 17 00:00:00 2001 From: heisendumb Date: Mon, 30 Oct 2017 00:44:00 -0200 Subject: [PATCH 16/45] edit USAGE.md --- docker/USAGE.md | 18 ++++++++++++++++++ docker/docker-compose.yml | 4 ++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docker/USAGE.md b/docker/USAGE.md index cd543c402..3c6ff700f 100644 --- a/docker/USAGE.md +++ b/docker/USAGE.md @@ -70,6 +70,24 @@ $ docker run -it -v /path/to/cool-sendgrid-python:/mnt/sendgrid-python sendgrid/ Note that the paths you specify in `-v` must be absolute. +# Docker Compose + +## Using tag's for versions - DockerHub + +### Edit variable TAG on .env/env_sample file + +```sh-session +$ sed -ie 's/TAG=latest/TAG=choice_a_version/g' +``` +### Run service using tags + +```sh-session +$ cd /path/to/sendgrid-python/docker +$ docker-compose up -d +``` + +# Specifying specific versions + # Testing Testing is easy! Run the container, `cd sendgrid`, and run `tox`. diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index d35772fd2..ed78e91ec 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -20,5 +20,5 @@ services: container_name: sendgrid-dev env_file: .env volumes: - - ${PATH_TO_SENDGRID-PYTHON}:/mnt/sendgrid-python - - ${PATH_TO_HTTP-CLIENT}:/mnt/python-http-client + - ${PATH_TO_SENDGRID-PYTHON_DEV}:/mnt/sendgrid-python + - ${PATH_TO_HTTP-CLIENT_DEV}:/mnt/python-http-client From a11de3e24bb5c94d39822f359d15e2c4a59e7124 Mon Sep 17 00:00:00 2001 From: heisendumb Date: Mon, 30 Oct 2017 02:11:14 -0200 Subject: [PATCH 17/45] issue #444 done --- docker/Makefile | 2 +- docker/USAGE.md | 45 ++++++++- docker/docker-compose.yml | 29 ++++-- docker/env/python-dev/sendgrid-python | 1 + docker/examples/templates/templates.py | 130 +++++++++++++++++++++++++ docker/sendgrid.env | 8 ++ 6 files changed, 202 insertions(+), 13 deletions(-) create mode 160000 docker/env/python-dev/sendgrid-python create mode 100644 docker/examples/templates/templates.py create mode 100644 docker/sendgrid.env diff --git a/docker/Makefile b/docker/Makefile index 1afc31189..76ccb73af 100644 --- a/docker/Makefile +++ b/docker/Makefile @@ -17,4 +17,4 @@ build-build: docker-compose up --build -d up: rm clean build-build - echo "Sendgrid dev environment is alive :D" + echo "Sendgrid-python environment is alive :D" diff --git a/docker/USAGE.md b/docker/USAGE.md index 3c6ff700f..d869a77ce 100644 --- a/docker/USAGE.md +++ b/docker/USAGE.md @@ -72,7 +72,16 @@ Note that the paths you specify in `-v` must be absolute. # Docker Compose -## Using tag's for versions - DockerHub + +# Quickstart + +1. Install docker-compose on your machine. +2. Must copy sendgrid.env to .env file. +3. Edit .env file for yours versions and paths. +4. Must create env folder for clone yours repo. +5. Have fun! :D + +## Using tag's for versions - DockerHub: ### Edit variable TAG on .env/env_sample file @@ -83,10 +92,40 @@ $ sed -ie 's/TAG=latest/TAG=choice_a_version/g' ```sh-session $ cd /path/to/sendgrid-python/docker -$ docker-compose up -d +$ docker-compose up -d sendgrid +``` + +## Specifying specific versions: + +### Edit variable TAG on .env/env_sample file + +```sh-session +$ sed -ie 's/SENDGRID_PYTHON_VERSION=vy.x.z/SENDGRID_PYTHON_VERSION=vx.y.z/g' +$ sed -ie 's/HTTP_CLIENT_VERSION=vy.x.z/HTTP_CLIENT_VERSION=vx.y.z/g' ``` -# Specifying specific versions +### Run service + +```sh-session +$ cd /path/to/sendgrid-python/docker +$ docker-compose up -d sendgrid-dev +``` + +## Specifying your own fork: + +### Edit variable TAG on .env/env_sample file + +```sh-session +$ sed -ie 's/TAG=latest/TAG=choice_a_version/g' +$ sed -ie 's/SENDGRID_PYTHON_VERSION=vy.x.z/SENDGRID_PYTHON_VERSION=vx.y.z/g' +``` + +### Run service + +```sh-session +$ cd /path/to/sendgrid-python/docker +$ docker-compose up -d sendgrid-beta +``` # Testing diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index ed78e91ec..2a435b39f 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -5,20 +5,31 @@ services: image: sendgrid/sendgrid-python:${TAG} restart: unless-stopped container_name: sendgrid-prod - volumes: - - ${PATH_TO_SENDGRID-PYTHON_PROD}:/mnt/sendgrid-python - - ${PATH_TO_HTTP-CLIENT_PROD}:/mnt/python-http-client - env_file: .env + tty: true + env_file: + - .env sendgrid-dev: build: context: . args: - - SENDGRID-PYTHON_VERSION: {SENDGRID-PYTHON_VERSION} - - HTTP-CLIENT_VERSION: {HTTP-CLIENT_VERSION} + - SENDGRID-PYTHON_VERSION=${SENDGRID_PYTHON_VERSION} + - HTTP-CLIENT_VERSION=${HTTP_CLIENT_VERSION} restart: unless-stopped container_name: sendgrid-dev - env_file: .env + tty: true + env_file: + - .env volumes: - - ${PATH_TO_SENDGRID-PYTHON_DEV}:/mnt/sendgrid-python - - ${PATH_TO_HTTP-CLIENT_DEV}:/mnt/python-http-client + - ${PATH_TO_SENDGRID_PYTHON_DEV}:/mnt/sendgrid-python + - ${PATH_TO_HTTP_CLIENT_DEV}:/mnt/python-http-client + + sendgrid-beta: + image: sendgrid/sendgrid-python:${TAG} + restart: unless-stopped + container_name: sendgrid-beta + tty: true + env_file: + - .env + volumes: + - ${PATH_TO_SENDGRID_PYTHON_FORK}:/root/sources/sendgrid-python/sendgrid diff --git a/docker/env/python-dev/sendgrid-python b/docker/env/python-dev/sendgrid-python new file mode 160000 index 000000000..28cf42f6d --- /dev/null +++ b/docker/env/python-dev/sendgrid-python @@ -0,0 +1 @@ +Subproject commit 28cf42f6d590695de7e7ecdedcb67e9d8d4729ac diff --git a/docker/examples/templates/templates.py b/docker/examples/templates/templates.py new file mode 100644 index 000000000..9d3d5dd4b --- /dev/null +++ b/docker/examples/templates/templates.py @@ -0,0 +1,130 @@ +import sendgrid +import json +import os + + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +################################################## +# Create a transactional template. # +# POST /templates # + +data = { + "name": "example_name" +} +response = sg.client.templates.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve all transactional templates. # +# GET /templates # + +response = sg.client.templates.get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Edit a transactional template. # +# PATCH /templates/{template_id} # + +data = { + "name": "new_example_name" +} +template_id = "test_url_param" +response = sg.client.templates._(template_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a single transactional template. # +# GET /templates/{template_id} # + +template_id = "test_url_param" +response = sg.client.templates._(template_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a template. # +# DELETE /templates/{template_id} # + +template_id = "test_url_param" +response = sg.client.templates._(template_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Create a new transactional template version. # +# POST /templates/{template_id}/versions # + +data = { + "active": 1, + "html_content": "<%body%>", + "name": "example_version_name", + "plain_content": "<%body%>", + "subject": "<%subject%>", + "template_id": "ddb96bbc-9b92-425e-8979-99464621b543" +} +template_id = "test_url_param" +response = sg.client.templates._(template_id).versions.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Edit a transactional template version. # +# PATCH /templates/{template_id}/versions/{version_id} # + +data = { + "active": 1, + "html_content": "<%body%>", + "name": "updated_example_name", + "plain_content": "<%body%>", + "subject": "<%subject%>" +} +template_id = "test_url_param" +version_id = "test_url_param" +response = sg.client.templates._(template_id).versions._(version_id).patch(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Retrieve a specific transactional template version. # +# GET /templates/{template_id}/versions/{version_id} # + +template_id = "test_url_param" +version_id = "test_url_param" +response = sg.client.templates._(template_id).versions._(version_id).get() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Delete a transactional template version. # +# DELETE /templates/{template_id}/versions/{version_id} # + +template_id = "test_url_param" +version_id = "test_url_param" +response = sg.client.templates._(template_id).versions._(version_id).delete() +print(response.status_code) +print(response.body) +print(response.headers) + +################################################## +# Activate a transactional template version. # +# POST /templates/{template_id}/versions/{version_id}/activate # + +template_id = "test_url_param" +version_id = "test_url_param" +response = sg.client.templates._(template_id).versions._(version_id).activate.post() +print(response.status_code) +print(response.body) +print(response.headers) + diff --git a/docker/sendgrid.env b/docker/sendgrid.env new file mode 100644 index 000000000..ace58fafa --- /dev/null +++ b/docker/sendgrid.env @@ -0,0 +1,8 @@ +TAG=latest +SENDGRID_PYTHON_VERSION="v3.6.1" +HTTP_CLIENT_VERSION="v1.2.4" +PATH_TO_SENDGRID_PYTHON_DEV=../env/python-dev/sendgrid-python +PATH_TO_HTTP_CLIENT_DEV=../env/python-dev/python-http-client +PATH_TO_SENDGRID_PYTHON_PROD=../env/python-prod/sendgrid-python +PATH_TO_HTTP_CLIENT_PROD=../env/python-prod/python-http-client +PATH_TO_SENDGRID_PYTHON_FORK=../env/python-fork/sendgrid-python From 6949b31bca679be851d329d9aae600b144e204bc Mon Sep 17 00:00:00 2001 From: d grossman Date: Fri, 3 Nov 2017 14:55:02 -0700 Subject: [PATCH 18/45] moved file, updated import --- {sendgrid/helpers/endpoints/ip => test}/test_unassigned.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) rename {sendgrid/helpers/endpoints/ip => test}/test_unassigned.py (96%) diff --git a/sendgrid/helpers/endpoints/ip/test_unassigned.py b/test/test_unassigned.py similarity index 96% rename from sendgrid/helpers/endpoints/ip/test_unassigned.py rename to test/test_unassigned.py index be5904018..d13451277 100644 --- a/sendgrid/helpers/endpoints/ip/test_unassigned.py +++ b/test/test_unassigned.py @@ -1,7 +1,8 @@ import json import pytest -from .unassigned import unassigned +from sendgrid.helpers.endpoints.ip.unassigned import unassigned + ret_json = '''[ { "ip": "167.89.21.3", From 91cb37e5b225067afc801272fce5563d3cf5fa57 Mon Sep 17 00:00:00 2001 From: mbernier Date: Tue, 12 Dec 2017 08:20:58 -0700 Subject: [PATCH 19/45] removed extra examples dir --- .../examples/accesssettings/accesssettings.py | 84 ---- docker/examples/alerts/alerts.py | 63 --- docker/examples/apikeys/apikeys.py | 85 ---- docker/examples/asm/asm.py | 174 -------- docker/examples/browsers/browsers.py | 17 - docker/examples/campaigns/campaigns.py | 154 ------- docker/examples/categories/categories.py | 37 -- docker/examples/clients/clients.py | 28 -- docker/examples/contactdb/contactdb.py | 396 ------------------ docker/examples/devices/devices.py | 17 - docker/examples/geo/geo.py | 17 - docker/examples/helpers/mail/mail_example.py | 219 ---------- docker/examples/ips/ips.py | 155 ------- docker/examples/mail/mail.py | 174 -------- .../mailboxproviders/mailboxproviders.py | 17 - docker/examples/mailsettings/mailsettings.py | 220 ---------- .../partnersettings/partnersettings.py | 40 -- docker/examples/scopes/scopes.py | 16 - docker/examples/senders/senders.py | 99 ----- docker/examples/stats/stats.py | 17 - docker/examples/subusers/subusers.py | 170 -------- docker/examples/suppression/suppression.py | 202 --------- docker/examples/templates/templates.py | 130 ------ .../trackingsettings/trackingsettings.py | 111 ----- docker/examples/user/user.py | 294 ------------- docker/examples/whitelabel/whitelabel.py | 311 -------------- 26 files changed, 3247 deletions(-) delete mode 100644 docker/examples/accesssettings/accesssettings.py delete mode 100644 docker/examples/alerts/alerts.py delete mode 100644 docker/examples/apikeys/apikeys.py delete mode 100644 docker/examples/asm/asm.py delete mode 100644 docker/examples/browsers/browsers.py delete mode 100644 docker/examples/campaigns/campaigns.py delete mode 100644 docker/examples/categories/categories.py delete mode 100644 docker/examples/clients/clients.py delete mode 100644 docker/examples/contactdb/contactdb.py delete mode 100644 docker/examples/devices/devices.py delete mode 100644 docker/examples/geo/geo.py delete mode 100644 docker/examples/helpers/mail/mail_example.py delete mode 100644 docker/examples/ips/ips.py delete mode 100644 docker/examples/mail/mail.py delete mode 100644 docker/examples/mailboxproviders/mailboxproviders.py delete mode 100644 docker/examples/mailsettings/mailsettings.py delete mode 100644 docker/examples/partnersettings/partnersettings.py delete mode 100644 docker/examples/scopes/scopes.py delete mode 100644 docker/examples/senders/senders.py delete mode 100644 docker/examples/stats/stats.py delete mode 100644 docker/examples/subusers/subusers.py delete mode 100644 docker/examples/suppression/suppression.py delete mode 100644 docker/examples/templates/templates.py delete mode 100644 docker/examples/trackingsettings/trackingsettings.py delete mode 100644 docker/examples/user/user.py delete mode 100644 docker/examples/whitelabel/whitelabel.py diff --git a/docker/examples/accesssettings/accesssettings.py b/docker/examples/accesssettings/accesssettings.py deleted file mode 100644 index aac0e4a54..000000000 --- a/docker/examples/accesssettings/accesssettings.py +++ /dev/null @@ -1,84 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve all recent access attempts # -# GET /access_settings/activity # - -params = {'limit': 1} -response = sg.client.access_settings.activity.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add one or more IPs to the whitelist # -# POST /access_settings/whitelist # - -data = { - "ips": [ - { - "ip": "192.168.1.1" - }, - { - "ip": "192.*.*.*" - }, - { - "ip": "192.168.1.3/32" - } - ] -} -response = sg.client.access_settings.whitelist.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a list of currently whitelisted IPs # -# GET /access_settings/whitelist # - -response = sg.client.access_settings.whitelist.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Remove one or more IPs from the whitelist # -# DELETE /access_settings/whitelist # - -data = { - "ids": [ - 1, - 2, - 3 - ] -} -response = sg.client.access_settings.whitelist.delete(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a specific whitelisted IP # -# GET /access_settings/whitelist/{rule_id} # - -rule_id = "test_url_param" -response = sg.client.access_settings.whitelist._(rule_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Remove a specific IP from the whitelist # -# DELETE /access_settings/whitelist/{rule_id} # - -rule_id = "test_url_param" -response = sg.client.access_settings.whitelist._(rule_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/alerts/alerts.py b/docker/examples/alerts/alerts.py deleted file mode 100644 index e30d48748..000000000 --- a/docker/examples/alerts/alerts.py +++ /dev/null @@ -1,63 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create a new Alert # -# POST /alerts # - -data = { - "email_to": "example@example.com", - "frequency": "daily", - "type": "stats_notification" -} -response = sg.client.alerts.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all alerts # -# GET /alerts # - -response = sg.client.alerts.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update an alert # -# PATCH /alerts/{alert_id} # - -data = { - "email_to": "example@example.com" -} -alert_id = "test_url_param" -response = sg.client.alerts._(alert_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a specific alert # -# GET /alerts/{alert_id} # - -alert_id = "test_url_param" -response = sg.client.alerts._(alert_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete an alert # -# DELETE /alerts/{alert_id} # - -alert_id = "test_url_param" -response = sg.client.alerts._(alert_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/apikeys/apikeys.py b/docker/examples/apikeys/apikeys.py deleted file mode 100644 index 42c3afa10..000000000 --- a/docker/examples/apikeys/apikeys.py +++ /dev/null @@ -1,85 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create API keys # -# POST /api_keys # - -data = { - "name": "My API Key", - "sample": "data", - "scopes": [ - "mail.send", - "alerts.create", - "alerts.read" - ] -} -response = sg.client.api_keys.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all API Keys belonging to the authenticated user # -# GET /api_keys # - -params = {'limit': 1} -response = sg.client.api_keys.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update the name & scopes of an API Key # -# PUT /api_keys/{api_key_id} # - -data = { - "name": "A New Hope", - "scopes": [ - "user.profile.read", - "user.profile.update" - ] -} -api_key_id = "test_url_param" -response = sg.client.api_keys._(api_key_id).put(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update API keys # -# PATCH /api_keys/{api_key_id} # - -data = { - "name": "A New Hope" -} -api_key_id = "test_url_param" -response = sg.client.api_keys._(api_key_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve an existing API Key # -# GET /api_keys/{api_key_id} # - -api_key_id = "test_url_param" -response = sg.client.api_keys._(api_key_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete API keys # -# DELETE /api_keys/{api_key_id} # - -api_key_id = "test_url_param" -response = sg.client.api_keys._(api_key_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/asm/asm.py b/docker/examples/asm/asm.py deleted file mode 100644 index 43130cf06..000000000 --- a/docker/examples/asm/asm.py +++ /dev/null @@ -1,174 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create a new suppression group # -# POST /asm/groups # - -data = { - "description": "Suggestions for products our users might like.", - "is_default": True, - "name": "Product Suggestions" -} -response = sg.client.asm.groups.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve information about multiple suppression groups # -# GET /asm/groups # - -params = {'id': 1} -response = sg.client.asm.groups.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a suppression group. # -# PATCH /asm/groups/{group_id} # - -data = { - "description": "Suggestions for items our users might like.", - "id": 103, - "name": "Item Suggestions" -} -group_id = "test_url_param" -response = sg.client.asm.groups._(group_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Get information on a single suppression group. # -# GET /asm/groups/{group_id} # - -group_id = "test_url_param" -response = sg.client.asm.groups._(group_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a suppression group. # -# DELETE /asm/groups/{group_id} # - -group_id = "test_url_param" -response = sg.client.asm.groups._(group_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add suppressions to a suppression group # -# POST /asm/groups/{group_id}/suppressions # - -data = { - "recipient_emails": [ - "test1@example.com", - "test2@example.com" - ] -} -group_id = "test_url_param" -response = sg.client.asm.groups._(group_id).suppressions.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all suppressions for a suppression group # -# GET /asm/groups/{group_id}/suppressions # - -group_id = "test_url_param" -response = sg.client.asm.groups._(group_id).suppressions.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Search for suppressions within a group # -# POST /asm/groups/{group_id}/suppressions/search # - -data = { - "recipient_emails": [ - "exists1@example.com", - "exists2@example.com", - "doesnotexists@example.com" - ] -} -group_id = "test_url_param" -response = sg.client.asm.groups._(group_id).suppressions.search.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a suppression from a suppression group # -# DELETE /asm/groups/{group_id}/suppressions/{email} # - -group_id = "test_url_param" -email = "test_url_param" -response = sg.client.asm.groups._(group_id).suppressions._(email).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all suppressions # -# GET /asm/suppressions # - -response = sg.client.asm.suppressions.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add recipient addresses to the global suppression group. # -# POST /asm/suppressions/global # - -data = { - "recipient_emails": [ - "test1@example.com", - "test2@example.com" - ] -} -response = sg.client.asm.suppressions._("global").post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a Global Suppression # -# GET /asm/suppressions/global/{email} # - -email = "test_url_param" -response = sg.client.asm.suppressions._("global")._(email).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a Global Suppression # -# DELETE /asm/suppressions/global/{email} # - -email = "test_url_param" -response = sg.client.asm.suppressions._("global")._(email).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all suppression groups for an email address # -# GET /asm/suppressions/{email} # - -email = "test_url_param" -response = sg.client.asm.suppressions._(email).get() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/browsers/browsers.py b/docker/examples/browsers/browsers.py deleted file mode 100644 index c123c12e5..000000000 --- a/docker/examples/browsers/browsers.py +++ /dev/null @@ -1,17 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve email statistics by browser. # -# GET /browsers/stats # - -params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'browsers': 'test_string', 'limit': 'test_string', 'offset': 'test_string', 'start_date': '2016-01-01'} -response = sg.client.browsers.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/campaigns/campaigns.py b/docker/examples/campaigns/campaigns.py deleted file mode 100644 index c77fc878b..000000000 --- a/docker/examples/campaigns/campaigns.py +++ /dev/null @@ -1,154 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create a Campaign # -# POST /campaigns # - -data = { - "categories": [ - "spring line" - ], - "custom_unsubscribe_url": "", - "html_content": "

Check out our spring line!

", - "ip_pool": "marketing", - "list_ids": [ - 110, - 124 - ], - "plain_content": "Check out our spring line!", - "segment_ids": [ - 110 - ], - "sender_id": 124451, - "subject": "New Products for Spring!", - "suppression_group_id": 42, - "title": "March Newsletter" -} -response = sg.client.campaigns.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all Campaigns # -# GET /campaigns # - -params = {'limit': 1, 'offset': 1} -response = sg.client.campaigns.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a Campaign # -# PATCH /campaigns/{campaign_id} # - -data = { - "categories": [ - "summer line" - ], - "html_content": "

Check out our summer line!

", - "plain_content": "Check out our summer line!", - "subject": "New Products for Summer!", - "title": "May Newsletter" -} -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a single campaign # -# GET /campaigns/{campaign_id} # - -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a Campaign # -# DELETE /campaigns/{campaign_id} # - -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a Scheduled Campaign # -# PATCH /campaigns/{campaign_id}/schedules # - -data = { - "send_at": 1489451436 -} -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).schedules.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Schedule a Campaign # -# POST /campaigns/{campaign_id}/schedules # - -data = { - "send_at": 1489771528 -} -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).schedules.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# View Scheduled Time of a Campaign # -# GET /campaigns/{campaign_id}/schedules # - -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).schedules.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Unschedule a Scheduled Campaign # -# DELETE /campaigns/{campaign_id}/schedules # - -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).schedules.delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Send a Campaign # -# POST /campaigns/{campaign_id}/schedules/now # - -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).schedules.now.post() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Send a Test Campaign # -# POST /campaigns/{campaign_id}/schedules/test # - -data = { - "to": "your.email@example.com" -} -campaign_id = "test_url_param" -response = sg.client.campaigns._(campaign_id).schedules.test.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/categories/categories.py b/docker/examples/categories/categories.py deleted file mode 100644 index 7984f0fe0..000000000 --- a/docker/examples/categories/categories.py +++ /dev/null @@ -1,37 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve all categories # -# GET /categories # - -params = {'category': 'test_string', 'limit': 1, 'offset': 1} -response = sg.client.categories.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve Email Statistics for Categories # -# GET /categories/stats # - -params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01', 'categories': 'test_string'} -response = sg.client.categories.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve sums of email stats for each category [Needs: Stats object defined, has category ID?] # -# GET /categories/stats/sums # - -params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'limit': 1, 'sort_by_metric': 'test_string', 'offset': 1, 'start_date': '2016-01-01', 'sort_by_direction': 'asc'} -response = sg.client.categories.stats.sums.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/clients/clients.py b/docker/examples/clients/clients.py deleted file mode 100644 index 7831ef78f..000000000 --- a/docker/examples/clients/clients.py +++ /dev/null @@ -1,28 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve email statistics by client type. # -# GET /clients/stats # - -params = {'aggregated_by': 'day', 'start_date': '2016-01-01', 'end_date': '2016-04-01'} -response = sg.client.clients.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve stats by a specific client type. # -# GET /clients/{client_type}/stats # - -params = {'aggregated_by': 'day', 'start_date': '2016-01-01', 'end_date': '2016-04-01'} -client_type = "test_url_param" -response = sg.client.clients._(client_type).stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/contactdb/contactdb.py b/docker/examples/contactdb/contactdb.py deleted file mode 100644 index c234d7724..000000000 --- a/docker/examples/contactdb/contactdb.py +++ /dev/null @@ -1,396 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create a Custom Field # -# POST /contactdb/custom_fields # - -data = { - "name": "pet", - "type": "text" -} -response = sg.client.contactdb.custom_fields.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all custom fields # -# GET /contactdb/custom_fields # - -response = sg.client.contactdb.custom_fields.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a Custom Field # -# GET /contactdb/custom_fields/{custom_field_id} # - -custom_field_id = "test_url_param" -response = sg.client.contactdb.custom_fields._(custom_field_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a Custom Field # -# DELETE /contactdb/custom_fields/{custom_field_id} # - -custom_field_id = "test_url_param" -response = sg.client.contactdb.custom_fields._(custom_field_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Create a List # -# POST /contactdb/lists # - -data = { - "name": "your list name" -} -response = sg.client.contactdb.lists.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all lists # -# GET /contactdb/lists # - -response = sg.client.contactdb.lists.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete Multiple lists # -# DELETE /contactdb/lists # - -data = [ - 1, - 2, - 3, - 4 -] -response = sg.client.contactdb.lists.delete(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a List # -# PATCH /contactdb/lists/{list_id} # - -data = { - "name": "newlistname" -} -params = {'list_id': 1} -list_id = "test_url_param" -response = sg.client.contactdb.lists._(list_id).patch(request_body=data, query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a single list # -# GET /contactdb/lists/{list_id} # - -params = {'list_id': 1} -list_id = "test_url_param" -response = sg.client.contactdb.lists._(list_id).get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a List # -# DELETE /contactdb/lists/{list_id} # - -params = {'delete_contacts': 'true'} -list_id = "test_url_param" -response = sg.client.contactdb.lists._(list_id).delete(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add Multiple Recipients to a List # -# POST /contactdb/lists/{list_id}/recipients # - -data = [ - "recipient_id1", - "recipient_id2" -] -list_id = "test_url_param" -response = sg.client.contactdb.lists._(list_id).recipients.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all recipients on a List # -# GET /contactdb/lists/{list_id}/recipients # - -params = {'page': 1, 'page_size': 1} -list_id = "test_url_param" -response = sg.client.contactdb.lists._(list_id).recipients.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add a Single Recipient to a List # -# POST /contactdb/lists/{list_id}/recipients/{recipient_id} # - -list_id = "test_url_param" -recipient_id = "test_url_param" -response = sg.client.contactdb.lists._(list_id).recipients._(recipient_id).post() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a Single Recipient from a Single List # -# DELETE /contactdb/lists/{list_id}/recipients/{recipient_id} # - -params = {'recipient_id': 1, 'list_id': 1} -list_id = "test_url_param" -recipient_id = "test_url_param" -response = sg.client.contactdb.lists._(list_id).recipients._(recipient_id).delete(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update Recipient # -# PATCH /contactdb/recipients # - -data = [ - { - "email": "jones@example.com", - "first_name": "Guy", - "last_name": "Jones" - } -] -response = sg.client.contactdb.recipients.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add recipients # -# POST /contactdb/recipients # - -data = [ - { - "age": 25, - "email": "example@example.com", - "first_name": "", - "last_name": "User" - }, - { - "age": 25, - "email": "example2@example.com", - "first_name": "Example", - "last_name": "User" - } -] -response = sg.client.contactdb.recipients.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve recipients # -# GET /contactdb/recipients # - -params = {'page': 1, 'page_size': 1} -response = sg.client.contactdb.recipients.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete Recipient # -# DELETE /contactdb/recipients # - -data = [ - "recipient_id1", - "recipient_id2" -] -response = sg.client.contactdb.recipients.delete(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve the count of billable recipients # -# GET /contactdb/recipients/billable_count # - -response = sg.client.contactdb.recipients.billable_count.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a Count of Recipients # -# GET /contactdb/recipients/count # - -response = sg.client.contactdb.recipients.count.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve recipients matching search criteria # -# GET /contactdb/recipients/search # - -params = {'{field_name}': 'test_string'} -response = sg.client.contactdb.recipients.search.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a single recipient # -# GET /contactdb/recipients/{recipient_id} # - -recipient_id = "test_url_param" -response = sg.client.contactdb.recipients._(recipient_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a Recipient # -# DELETE /contactdb/recipients/{recipient_id} # - -recipient_id = "test_url_param" -response = sg.client.contactdb.recipients._(recipient_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve the lists that a recipient is on # -# GET /contactdb/recipients/{recipient_id}/lists # - -recipient_id = "test_url_param" -response = sg.client.contactdb.recipients._(recipient_id).lists.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve reserved fields # -# GET /contactdb/reserved_fields # - -response = sg.client.contactdb.reserved_fields.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Create a Segment # -# POST /contactdb/segments # - -data = { - "conditions": [ - { - "and_or": "", - "field": "last_name", - "operator": "eq", - "value": "Miller" - }, - { - "and_or": "and", - "field": "last_clicked", - "operator": "gt", - "value": "01/02/2015" - }, - { - "and_or": "or", - "field": "clicks.campaign_identifier", - "operator": "eq", - "value": "513" - } - ], - "list_id": 4, - "name": "Last Name Miller" -} -response = sg.client.contactdb.segments.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all segments # -# GET /contactdb/segments # - -response = sg.client.contactdb.segments.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a segment # -# PATCH /contactdb/segments/{segment_id} # - -data = { - "conditions": [ - { - "and_or": "", - "field": "last_name", - "operator": "eq", - "value": "Miller" - } - ], - "list_id": 5, - "name": "The Millers" -} -params = {'segment_id': 'test_string'} -segment_id = "test_url_param" -response = sg.client.contactdb.segments._(segment_id).patch(request_body=data, query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a segment # -# GET /contactdb/segments/{segment_id} # - -params = {'segment_id': 1} -segment_id = "test_url_param" -response = sg.client.contactdb.segments._(segment_id).get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a segment # -# DELETE /contactdb/segments/{segment_id} # - -params = {'delete_contacts': 'true'} -segment_id = "test_url_param" -response = sg.client.contactdb.segments._(segment_id).delete(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve recipients on a segment # -# GET /contactdb/segments/{segment_id}/recipients # - -params = {'page': 1, 'page_size': 1} -segment_id = "test_url_param" -response = sg.client.contactdb.segments._(segment_id).recipients.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/devices/devices.py b/docker/examples/devices/devices.py deleted file mode 100644 index 108e98452..000000000 --- a/docker/examples/devices/devices.py +++ /dev/null @@ -1,17 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve email statistics by device type. # -# GET /devices/stats # - -params = {'aggregated_by': 'day', 'limit': 1, 'start_date': '2016-01-01', 'end_date': '2016-04-01', 'offset': 1} -response = sg.client.devices.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/geo/geo.py b/docker/examples/geo/geo.py deleted file mode 100644 index 7d58ec085..000000000 --- a/docker/examples/geo/geo.py +++ /dev/null @@ -1,17 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve email statistics by country and state/province. # -# GET /geo/stats # - -params = {'end_date': '2016-04-01', 'country': 'US', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01'} -response = sg.client.geo.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/helpers/mail/mail_example.py b/docker/examples/helpers/mail/mail_example.py deleted file mode 100644 index bfd8ea718..000000000 --- a/docker/examples/helpers/mail/mail_example.py +++ /dev/null @@ -1,219 +0,0 @@ -import json -import os -import urllib2 -from sendgrid.helpers.mail import * -from sendgrid import * - -# NOTE: you will need move this file to the root -# directory of this project to execute properly. - - -def build_hello_email(): - """Minimum required to send an email""" - from_email = Email("test@example.com") - subject = "Hello World from the SendGrid Python Library" - to_email = Email("test@example.com") - content = Content("text/plain", "some text here") - mail = Mail(from_email, subject, to_email, content) - mail.personalizations[0].add_to(Email("test2@example.com")) - - return mail.get() - - -def build_personalization(personalization): - """Build personalization mock instance from a mock dict""" - mock_personalization = Personalization() - for to_addr in personalization['to_list']: - personalization.add_to(to_addr) - - for cc_addr in personalization['cc_list']: - personalization.add_to(cc_addr) - - for bcc_addr in personalization['bcc_list']: - personalization.add_bc(bcc_addr) - - for header in personalization['headers']: - personalization.add_header(header) - - for substitution in personalization['substitutions']: - personalization.add_substitution(substitution) - - for arg in personalization['custom_args']: - personalization.add_custom_arg(arg) - - personalization.subject = personalization['subject'] - personalization.send_at = personalization['send_at'] - return mock_personalization - - -def get_mock_personalization_dict(): - """Get a dict of personalization mock.""" - mock_pers = dict() - - mock_pers['to_list'] = [Email("test1@example.com", - "Example User"), - Email("test2@example.com", - "Example User")] - - mock_pers['cc_list'] = [Email("test3@example.com", - "Example User"), - Email("test4@example.com", - "Example User")] - - mock_pers['bcc_list'] = [Email("test5@example.com"), - Email("test6@example.com")] - - mock_pers['subject'] = ("Hello World from the Personalized " - "SendGrid Python Library") - - mock_pers['headers'] = [Header("X-Test", "test"), - Header("X-Mock", "true")] - - mock_pers['substitutions'] = [Substitution("%name%", "Example User"), - Substitution("%city%", "Denver")] - - mock_pers['custom_args'] = [CustomArg("user_id", "343"), - CustomArg("type", "marketing")] - - mock_pers['send_at'] = 1443636843 - return mock_pers - - -def build_attachment1(): - """Build attachment mock.""" - attachment = Attachment() - attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl" - "Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12") - attachment.type = "application/pdf" - attachment.filename = "balance_001.pdf" - attachment.disposition = "attachment" - attachment.content_id = "Balance Sheet" - return attachment - - -def build_attachment2(): - """Build attachment mock.""" - attachment = Attachment() - attachment.content = "BwdW" - attachment.type = "image/png" - attachment.filename = "banner.png" - attachment.disposition = "inline" - attachment.content_id = "Banner" - return attachment - - -def build_mail_settings(): - """Build mail settings mock.""" - mail_settings = MailSettings() - mail_settings.bcc_settings = BCCSettings(True, Email("test@example.com")) - mail_settings.bypass_list_management = BypassListManagement(True) - mail_settings.footer_settings = FooterSettings(True, "Footer Text", - ("Footer " - "Text")) - mail_settings.sandbox_mode = SandBoxMode(True) - mail_settings.spam_check = SpamCheck(True, 1, - "https://spamcatcher.sendgrid.com") - return mail_settings - - -def build_tracking_settings(): - """Build tracking settings mock.""" - tracking_settings = TrackingSettings() - tracking_settings.click_tracking = ClickTracking(True, True) - tracking_settings.open_tracking = OpenTracking(True, - ("Optional tag to " - "replace with the" - "open image in the " - "body of the message")) - - subs_track = SubscriptionTracking(True, - ("text to insert into the " - "text/plain portion of the" - " message"), - ("html to insert " - "into the text/html portion of " - "the message"), - ("Optional tag to replace with " - "the open image in the body of " - "the message")) - - tracking_settings.subscription_tracking = subs_track - tracking_settings.ganalytics = Ganalytics(True, "some source", - "some medium", "some term", - "some_content", "some_campaign") - return tracking_settings - - -def build_kitchen_sink(): - """All settings set""" - mail = Mail() - - mail.from_email = Email("test@example.com", "Example User") - mail.subject = "Hello World from the SendGrid Python Library" - - personalization = get_mock_personalization_dict() - mail.add_personalization(build_personalization(personalization)) - mail.add_personalization(build_personalization(personalization)) - - mail.add_content(Content("text/plain", "some text here")) - mail.add_content(Content("text/html", ("some text " - "here"))) - - mail.add_attachment(build_attachment1()) - mail.add_attachment(build_attachment2()) - - mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932" - - mail.add_section(Section("%section1%", "Substitution Text for Section 1")) - mail.add_section(Section("%section2%", "Substitution Text for Section 2")) - - mail.add_header(Header("X-Test1", "test1")) - mail.add_header(Header("X-Test3", "test2")) - - mail.add_category(Category("May")) - mail.add_category(Category("2016")) - - mail.add_custom_arg(CustomArg("campaign", "welcome")) - mail.add_custom_arg(CustomArg("weekday", "morning")) - - mail.send_at = 1443636842 - - # This must be a valid [batch ID] - # (https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) to work - # mail.set_batch_id("N2VkYjBjYWItMGU4OC0xMWU2LWJhMzYtZjQ1Yzg5OTBkNzkxLWM5ZTUyZjNhOA") - mail.asm = ASM(99, [4, 5, 6, 7, 8]) - mail.ip_pool_name = "24" - mail.mail_settings = build_mail_settings() - mail.tracking_settings = build_tracking_settings() - mail.reply_to = Email("test@example.com") - - return mail.get() - - -def send_hello_email(): - # Assumes you set your environment variable: - # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key - sg = SendGridAPIClient() - data = build_hello_email() - response = sg.client.mail.send.post(request_body=data) - print(response.status_code) - print(response.headers) - print(response.body) - - -def send_kitchen_sink(): - # Assumes you set your environment variable: - # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key - sg = SendGridAPIClient() - data = build_kitchen_sink() - response = sg.client.mail.send.post(request_body=data) - print(response.status_code) - print(response.headers) - print(response.body) - - -# this will actually send an email -send_hello_email() - -# this will only send an email if you set SandBox Mode to False -send_kitchen_sink() diff --git a/docker/examples/ips/ips.py b/docker/examples/ips/ips.py deleted file mode 100644 index 6c48ae306..000000000 --- a/docker/examples/ips/ips.py +++ /dev/null @@ -1,155 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve all IP addresses # -# GET /ips # - -params = {'subuser': 'test_string', 'ip': 'test_string', 'limit': 1, 'exclude_whitelabels': 'true', 'offset': 1} -response = sg.client.ips.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all assigned IPs # -# GET /ips/assigned # - -response = sg.client.ips.assigned.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Create an IP pool. # -# POST /ips/pools # - -data = { - "name": "marketing" -} -response = sg.client.ips.pools.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all IP pools. # -# GET /ips/pools # - -response = sg.client.ips.pools.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update an IP pools name. # -# PUT /ips/pools/{pool_name} # - -data = { - "name": "new_pool_name" -} -pool_name = "test_url_param" -response = sg.client.ips.pools._(pool_name).put(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all IPs in a specified pool. # -# GET /ips/pools/{pool_name} # - -pool_name = "test_url_param" -response = sg.client.ips.pools._(pool_name).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete an IP pool. # -# DELETE /ips/pools/{pool_name} # - -pool_name = "test_url_param" -response = sg.client.ips.pools._(pool_name).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add an IP address to a pool # -# POST /ips/pools/{pool_name}/ips # - -data = { - "ip": "0.0.0.0" -} -pool_name = "test_url_param" -response = sg.client.ips.pools._(pool_name).ips.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Remove an IP address from a pool. # -# DELETE /ips/pools/{pool_name}/ips/{ip} # - -pool_name = "test_url_param" -ip = "test_url_param" -response = sg.client.ips.pools._(pool_name).ips._(ip).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add an IP to warmup # -# POST /ips/warmup # - -data = { - "ip": "0.0.0.0" -} -response = sg.client.ips.warmup.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all IPs currently in warmup # -# GET /ips/warmup # - -response = sg.client.ips.warmup.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve warmup status for a specific IP address # -# GET /ips/warmup/{ip_address} # - -ip_address = "test_url_param" -response = sg.client.ips.warmup._(ip_address).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Remove an IP from warmup # -# DELETE /ips/warmup/{ip_address} # - -ip_address = "test_url_param" -response = sg.client.ips.warmup._(ip_address).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all IP pools an IP address belongs to # -# GET /ips/{ip_address} # - -ip_address = "test_url_param" -response = sg.client.ips._(ip_address).get() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/mail/mail.py b/docker/examples/mail/mail.py deleted file mode 100644 index fef420e87..000000000 --- a/docker/examples/mail/mail.py +++ /dev/null @@ -1,174 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create a batch ID # -# POST /mail/batch # - -response = sg.client.mail.batch.post() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Validate batch ID # -# GET /mail/batch/{batch_id} # - -batch_id = "test_url_param" -response = sg.client.mail.batch._(batch_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# v3 Mail Send # -# POST /mail/send # -# This endpoint has a helper, check it out [here](https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/helpers/mail/README.md). - -data = { - "asm": { - "group_id": 1, - "groups_to_display": [ - 1, - 2, - 3 - ] - }, - "attachments": [ - { - "content": "[BASE64 encoded content block here]", - "content_id": "ii_139db99fdb5c3704", - "disposition": "inline", - "filename": "file1.jpg", - "name": "file1", - "type": "jpg" - } - ], - "batch_id": "[YOUR BATCH ID GOES HERE]", - "categories": [ - "category1", - "category2" - ], - "content": [ - { - "type": "text/html", - "value": "

Hello, world!

" - } - ], - "custom_args": { - "New Argument 1": "New Value 1", - "activationAttempt": "1", - "customerAccountNumber": "[CUSTOMER ACCOUNT NUMBER GOES HERE]" - }, - "from": { - "email": "sam.smith@example.com", - "name": "Sam Smith" - }, - "headers": {}, - "ip_pool_name": "[YOUR POOL NAME GOES HERE]", - "mail_settings": { - "bcc": { - "email": "ben.doe@example.com", - "enable": True - }, - "bypass_list_management": { - "enable": True - }, - "footer": { - "enable": True, - "html": "

Thanks
The SendGrid Team

", - "text": "Thanks,/n The SendGrid Team" - }, - "sandbox_mode": { - "enable": False - }, - "spam_check": { - "enable": True, - "post_to_url": "http://example.com/compliance", - "threshold": 3 - } - }, - "personalizations": [ - { - "bcc": [ - { - "email": "sam.doe@example.com", - "name": "Sam Doe" - } - ], - "cc": [ - { - "email": "jane.doe@example.com", - "name": "Jane Doe" - } - ], - "custom_args": { - "New Argument 1": "New Value 1", - "activationAttempt": "1", - "customerAccountNumber": "[CUSTOMER ACCOUNT NUMBER GOES HERE]" - }, - "headers": { - "X-Accept-Language": "en", - "X-Mailer": "MyApp" - }, - "send_at": 1409348513, - "subject": "Hello, World!", - "substitutions": { - "id": "substitutions", - "type": "object" - }, - "to": [ - { - "email": "john.doe@example.com", - "name": "John Doe" - } - ] - } - ], - "reply_to": { - "email": "sam.smith@example.com", - "name": "Sam Smith" - }, - "sections": { - "section": { - ":sectionName1": "section 1 text", - ":sectionName2": "section 2 text" - } - }, - "send_at": 1409348513, - "subject": "Hello, World!", - "template_id": "[YOUR TEMPLATE ID GOES HERE]", - "tracking_settings": { - "click_tracking": { - "enable": True, - "enable_text": True - }, - "ganalytics": { - "enable": True, - "utm_campaign": "[NAME OF YOUR REFERRER SOURCE]", - "utm_content": "[USE THIS SPACE TO DIFFERENTIATE YOUR EMAIL FROM ADS]", - "utm_medium": "[NAME OF YOUR MARKETING MEDIUM e.g. email]", - "utm_name": "[NAME OF YOUR CAMPAIGN]", - "utm_term": "[IDENTIFY PAID KEYWORDS HERE]" - }, - "open_tracking": { - "enable": True, - "substitution_tag": "%opentrack" - }, - "subscription_tracking": { - "enable": True, - "html": "If you would like to unsubscribe and stop receiving these emails <% clickhere %>.", - "substitution_tag": "<%click here%>", - "text": "If you would like to unsubscribe and stop receiveing these emails <% click here %>." - } - } -} -response = sg.client.mail.send.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/mailboxproviders/mailboxproviders.py b/docker/examples/mailboxproviders/mailboxproviders.py deleted file mode 100644 index 1b75ecac5..000000000 --- a/docker/examples/mailboxproviders/mailboxproviders.py +++ /dev/null @@ -1,17 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve email statistics by mailbox provider. # -# GET /mailbox_providers/stats # - -params = {'end_date': '2016-04-01', 'mailbox_providers': 'test_string', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01'} -response = sg.client.mailbox_providers.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/mailsettings/mailsettings.py b/docker/examples/mailsettings/mailsettings.py deleted file mode 100644 index 18c57b960..000000000 --- a/docker/examples/mailsettings/mailsettings.py +++ /dev/null @@ -1,220 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve all mail settings # -# GET /mail_settings # - -params = {'limit': 1, 'offset': 1} -response = sg.client.mail_settings.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update address whitelist mail settings # -# PATCH /mail_settings/address_whitelist # - -data = { - "enabled": True, - "list": [ - "email1@example.com", - "example.com" - ] -} -response = sg.client.mail_settings.address_whitelist.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve address whitelist mail settings # -# GET /mail_settings/address_whitelist # - -response = sg.client.mail_settings.address_whitelist.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update BCC mail settings # -# PATCH /mail_settings/bcc # - -data = { - "email": "email@example.com", - "enabled": False -} -response = sg.client.mail_settings.bcc.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all BCC mail settings # -# GET /mail_settings/bcc # - -response = sg.client.mail_settings.bcc.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update bounce purge mail settings # -# PATCH /mail_settings/bounce_purge # - -data = { - "enabled": True, - "hard_bounces": 5, - "soft_bounces": 5 -} -response = sg.client.mail_settings.bounce_purge.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve bounce purge mail settings # -# GET /mail_settings/bounce_purge # - -response = sg.client.mail_settings.bounce_purge.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update footer mail settings # -# PATCH /mail_settings/footer # - -data = { - "enabled": True, - "html_content": "...", - "plain_content": "..." -} -response = sg.client.mail_settings.footer.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve footer mail settings # -# GET /mail_settings/footer # - -response = sg.client.mail_settings.footer.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update forward bounce mail settings # -# PATCH /mail_settings/forward_bounce # - -data = { - "email": "example@example.com", - "enabled": True -} -response = sg.client.mail_settings.forward_bounce.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve forward bounce mail settings # -# GET /mail_settings/forward_bounce # - -response = sg.client.mail_settings.forward_bounce.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update forward spam mail settings # -# PATCH /mail_settings/forward_spam # - -data = { - "email": "", - "enabled": False -} -response = sg.client.mail_settings.forward_spam.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve forward spam mail settings # -# GET /mail_settings/forward_spam # - -response = sg.client.mail_settings.forward_spam.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update plain content mail settings # -# PATCH /mail_settings/plain_content # - -data = { - "enabled": False -} -response = sg.client.mail_settings.plain_content.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve plain content mail settings # -# GET /mail_settings/plain_content # - -response = sg.client.mail_settings.plain_content.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update spam check mail settings # -# PATCH /mail_settings/spam_check # - -data = { - "enabled": True, - "max_score": 5, - "url": "url" -} -response = sg.client.mail_settings.spam_check.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve spam check mail settings # -# GET /mail_settings/spam_check # - -response = sg.client.mail_settings.spam_check.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update template mail settings # -# PATCH /mail_settings/template # - -data = { - "enabled": True, - "html_content": "<% body %>" -} -response = sg.client.mail_settings.template.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve legacy template mail settings # -# GET /mail_settings/template # - -response = sg.client.mail_settings.template.get() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/partnersettings/partnersettings.py b/docker/examples/partnersettings/partnersettings.py deleted file mode 100644 index 37f77f4e6..000000000 --- a/docker/examples/partnersettings/partnersettings.py +++ /dev/null @@ -1,40 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Returns a list of all partner settings. # -# GET /partner_settings # - -params = {'limit': 1, 'offset': 1} -response = sg.client.partner_settings.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Updates New Relic partner settings. # -# PATCH /partner_settings/new_relic # - -data = { - "enable_subuser_statistics": True, - "enabled": True, - "license_key": "" -} -response = sg.client.partner_settings.new_relic.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Returns all New Relic partner settings. # -# GET /partner_settings/new_relic # - -response = sg.client.partner_settings.new_relic.get() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/scopes/scopes.py b/docker/examples/scopes/scopes.py deleted file mode 100644 index 124f77d39..000000000 --- a/docker/examples/scopes/scopes.py +++ /dev/null @@ -1,16 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve a list of scopes for which this user has access. # -# GET /scopes # - -response = sg.client.scopes.get() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/senders/senders.py b/docker/examples/senders/senders.py deleted file mode 100644 index f21459b71..000000000 --- a/docker/examples/senders/senders.py +++ /dev/null @@ -1,99 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create a Sender Identity # -# POST /senders # - -data = { - "address": "123 Elm St.", - "address_2": "Apt. 456", - "city": "Denver", - "country": "United States", - "from": { - "email": "from@example.com", - "name": "Example INC" - }, - "nickname": "My Sender ID", - "reply_to": { - "email": "replyto@example.com", - "name": "Example INC" - }, - "state": "Colorado", - "zip": "80202" -} -response = sg.client.senders.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Get all Sender Identities # -# GET /senders # - -response = sg.client.senders.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a Sender Identity # -# PATCH /senders/{sender_id} # - -data = { - "address": "123 Elm St.", - "address_2": "Apt. 456", - "city": "Denver", - "country": "United States", - "from": { - "email": "from@example.com", - "name": "Example INC" - }, - "nickname": "My Sender ID", - "reply_to": { - "email": "replyto@example.com", - "name": "Example INC" - }, - "state": "Colorado", - "zip": "80202" -} -sender_id = "test_url_param" -response = sg.client.senders._(sender_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# View a Sender Identity # -# GET /senders/{sender_id} # - -sender_id = "test_url_param" -response = sg.client.senders._(sender_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a Sender Identity # -# DELETE /senders/{sender_id} # - -sender_id = "test_url_param" -response = sg.client.senders._(sender_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Resend Sender Identity Verification # -# POST /senders/{sender_id}/resend_verification # - -sender_id = "test_url_param" -response = sg.client.senders._(sender_id).resend_verification.post() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/stats/stats.py b/docker/examples/stats/stats.py deleted file mode 100644 index a7bf3362e..000000000 --- a/docker/examples/stats/stats.py +++ /dev/null @@ -1,17 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve global email statistics # -# GET /stats # - -params = {'aggregated_by': 'day', 'limit': 1, 'start_date': '2016-01-01', 'end_date': '2016-04-01', 'offset': 1} -response = sg.client.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/subusers/subusers.py b/docker/examples/subusers/subusers.py deleted file mode 100644 index 6aa91e535..000000000 --- a/docker/examples/subusers/subusers.py +++ /dev/null @@ -1,170 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create Subuser # -# POST /subusers # - -data = { - "email": "John@example.com", - "ips": [ - "1.1.1.1", - "2.2.2.2" - ], - "password": "johns_password", - "username": "John@example.com" -} -response = sg.client.subusers.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# List all Subusers # -# GET /subusers # - -params = {'username': 'test_string', 'limit': 1, 'offset': 1} -response = sg.client.subusers.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve Subuser Reputations # -# GET /subusers/reputations # - -params = {'usernames': 'test_string'} -response = sg.client.subusers.reputations.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve email statistics for your subusers. # -# GET /subusers/stats # - -params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01', 'subusers': 'test_string'} -response = sg.client.subusers.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve monthly stats for all subusers # -# GET /subusers/stats/monthly # - -params = {'subuser': 'test_string', 'limit': 1, 'sort_by_metric': 'test_string', 'offset': 1, 'date': 'test_string', 'sort_by_direction': 'asc'} -response = sg.client.subusers.stats.monthly.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve the totals for each email statistic metric for all subusers. # -# GET /subusers/stats/sums # - -params = {'end_date': '2016-04-01', 'aggregated_by': 'day', 'limit': 1, 'sort_by_metric': 'test_string', 'offset': 1, 'start_date': '2016-01-01', 'sort_by_direction': 'asc'} -response = sg.client.subusers.stats.sums.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Enable/disable a subuser # -# PATCH /subusers/{subuser_name} # - -data = { - "disabled": False -} -subuser_name = "test_url_param" -response = sg.client.subusers._(subuser_name).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a subuser # -# DELETE /subusers/{subuser_name} # - -subuser_name = "test_url_param" -response = sg.client.subusers._(subuser_name).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update IPs assigned to a subuser # -# PUT /subusers/{subuser_name}/ips # - -data = [ - "127.0.0.1" -] -subuser_name = "test_url_param" -response = sg.client.subusers._(subuser_name).ips.put(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update Monitor Settings for a subuser # -# PUT /subusers/{subuser_name}/monitor # - -data = { - "email": "example@example.com", - "frequency": 500 -} -subuser_name = "test_url_param" -response = sg.client.subusers._(subuser_name).monitor.put(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Create monitor settings # -# POST /subusers/{subuser_name}/monitor # - -data = { - "email": "example@example.com", - "frequency": 50000 -} -subuser_name = "test_url_param" -response = sg.client.subusers._(subuser_name).monitor.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve monitor settings for a subuser # -# GET /subusers/{subuser_name}/monitor # - -subuser_name = "test_url_param" -response = sg.client.subusers._(subuser_name).monitor.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete monitor settings # -# DELETE /subusers/{subuser_name}/monitor # - -subuser_name = "test_url_param" -response = sg.client.subusers._(subuser_name).monitor.delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve the monthly email statistics for a single subuser # -# GET /subusers/{subuser_name}/stats/monthly # - -params = {'date': 'test_string', 'sort_by_direction': 'asc', 'limit': 1, 'sort_by_metric': 'test_string', 'offset': 1} -subuser_name = "test_url_param" -response = sg.client.subusers._(subuser_name).stats.monthly.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/suppression/suppression.py b/docker/examples/suppression/suppression.py deleted file mode 100644 index abdaef76d..000000000 --- a/docker/examples/suppression/suppression.py +++ /dev/null @@ -1,202 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve all blocks # -# GET /suppression/blocks # - -params = {'start_time': 1, 'limit': 1, 'end_time': 1, 'offset': 1} -response = sg.client.suppression.blocks.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete blocks # -# DELETE /suppression/blocks # - -data = { - "delete_all": False, - "emails": [ - "example1@example.com", - "example2@example.com" - ] -} -response = sg.client.suppression.blocks.delete(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a specific block # -# GET /suppression/blocks/{email} # - -email = "test_url_param" -response = sg.client.suppression.blocks._(email).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a specific block # -# DELETE /suppression/blocks/{email} # - -email = "test_url_param" -response = sg.client.suppression.blocks._(email).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all bounces # -# GET /suppression/bounces # - -params = {'start_time': 1, 'end_time': 1} -response = sg.client.suppression.bounces.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete bounces # -# DELETE /suppression/bounces # - -data = { - "delete_all": True, - "emails": [ - "example@example.com", - "example2@example.com" - ] -} -response = sg.client.suppression.bounces.delete(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a Bounce # -# GET /suppression/bounces/{email} # - -email = "test_url_param" -response = sg.client.suppression.bounces._(email).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a bounce # -# DELETE /suppression/bounces/{email} # - -params = {'email_address': 'example@example.com'} -email = "test_url_param" -response = sg.client.suppression.bounces._(email).delete(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all invalid emails # -# GET /suppression/invalid_emails # - -params = {'start_time': 1, 'limit': 1, 'end_time': 1, 'offset': 1} -response = sg.client.suppression.invalid_emails.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete invalid emails # -# DELETE /suppression/invalid_emails # - -data = { - "delete_all": False, - "emails": [ - "example1@example.com", - "example2@example.com" - ] -} -response = sg.client.suppression.invalid_emails.delete(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a specific invalid email # -# GET /suppression/invalid_emails/{email} # - -email = "test_url_param" -response = sg.client.suppression.invalid_emails._(email).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a specific invalid email # -# DELETE /suppression/invalid_emails/{email} # - -email = "test_url_param" -response = sg.client.suppression.invalid_emails._(email).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a specific spam report # -# GET /suppression/spam_report/{email} # - -email = "test_url_param" -response = sg.client.suppression.spam_report._(email).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a specific spam report # -# DELETE /suppression/spam_report/{email} # - -email = "test_url_param" -response = sg.client.suppression.spam_report._(email).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all spam reports # -# GET /suppression/spam_reports # - -params = {'start_time': 1, 'limit': 1, 'end_time': 1, 'offset': 1} -response = sg.client.suppression.spam_reports.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete spam reports # -# DELETE /suppression/spam_reports # - -data = { - "delete_all": False, - "emails": [ - "example1@example.com", - "example2@example.com" - ] -} -response = sg.client.suppression.spam_reports.delete(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all global suppressions # -# GET /suppression/unsubscribes # - -params = {'start_time': 1, 'limit': 1, 'end_time': 1, 'offset': 1} -response = sg.client.suppression.unsubscribes.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/templates/templates.py b/docker/examples/templates/templates.py deleted file mode 100644 index 9d3d5dd4b..000000000 --- a/docker/examples/templates/templates.py +++ /dev/null @@ -1,130 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create a transactional template. # -# POST /templates # - -data = { - "name": "example_name" -} -response = sg.client.templates.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all transactional templates. # -# GET /templates # - -response = sg.client.templates.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Edit a transactional template. # -# PATCH /templates/{template_id} # - -data = { - "name": "new_example_name" -} -template_id = "test_url_param" -response = sg.client.templates._(template_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a single transactional template. # -# GET /templates/{template_id} # - -template_id = "test_url_param" -response = sg.client.templates._(template_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a template. # -# DELETE /templates/{template_id} # - -template_id = "test_url_param" -response = sg.client.templates._(template_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Create a new transactional template version. # -# POST /templates/{template_id}/versions # - -data = { - "active": 1, - "html_content": "<%body%>", - "name": "example_version_name", - "plain_content": "<%body%>", - "subject": "<%subject%>", - "template_id": "ddb96bbc-9b92-425e-8979-99464621b543" -} -template_id = "test_url_param" -response = sg.client.templates._(template_id).versions.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Edit a transactional template version. # -# PATCH /templates/{template_id}/versions/{version_id} # - -data = { - "active": 1, - "html_content": "<%body%>", - "name": "updated_example_name", - "plain_content": "<%body%>", - "subject": "<%subject%>" -} -template_id = "test_url_param" -version_id = "test_url_param" -response = sg.client.templates._(template_id).versions._(version_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a specific transactional template version. # -# GET /templates/{template_id}/versions/{version_id} # - -template_id = "test_url_param" -version_id = "test_url_param" -response = sg.client.templates._(template_id).versions._(version_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a transactional template version. # -# DELETE /templates/{template_id}/versions/{version_id} # - -template_id = "test_url_param" -version_id = "test_url_param" -response = sg.client.templates._(template_id).versions._(version_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Activate a transactional template version. # -# POST /templates/{template_id}/versions/{version_id}/activate # - -template_id = "test_url_param" -version_id = "test_url_param" -response = sg.client.templates._(template_id).versions._(version_id).activate.post() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/trackingsettings/trackingsettings.py b/docker/examples/trackingsettings/trackingsettings.py deleted file mode 100644 index 80dbe243a..000000000 --- a/docker/examples/trackingsettings/trackingsettings.py +++ /dev/null @@ -1,111 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Retrieve Tracking Settings # -# GET /tracking_settings # - -params = {'limit': 1, 'offset': 1} -response = sg.client.tracking_settings.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update Click Tracking Settings # -# PATCH /tracking_settings/click # - -data = { - "enabled": True -} -response = sg.client.tracking_settings.click.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve Click Track Settings # -# GET /tracking_settings/click # - -response = sg.client.tracking_settings.click.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update Google Analytics Settings # -# PATCH /tracking_settings/google_analytics # - -data = { - "enabled": True, - "utm_campaign": "website", - "utm_content": "", - "utm_medium": "email", - "utm_source": "sendgrid.com", - "utm_term": "" -} -response = sg.client.tracking_settings.google_analytics.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve Google Analytics Settings # -# GET /tracking_settings/google_analytics # - -response = sg.client.tracking_settings.google_analytics.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update Open Tracking Settings # -# PATCH /tracking_settings/open # - -data = { - "enabled": True -} -response = sg.client.tracking_settings.open.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Get Open Tracking Settings # -# GET /tracking_settings/open # - -response = sg.client.tracking_settings.open.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update Subscription Tracking Settings # -# PATCH /tracking_settings/subscription # - -data = { - "enabled": True, - "html_content": "html content", - "landing": "landing page html", - "plain_content": "text content", - "replace": "replacement tag", - "url": "url" -} -response = sg.client.tracking_settings.subscription.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve Subscription Tracking Settings # -# GET /tracking_settings/subscription # - -response = sg.client.tracking_settings.subscription.get() -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/user/user.py b/docker/examples/user/user.py deleted file mode 100644 index 9e3f24766..000000000 --- a/docker/examples/user/user.py +++ /dev/null @@ -1,294 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Get a user's account information. # -# GET /user/account # - -response = sg.client.user.account.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve your credit balance # -# GET /user/credits # - -response = sg.client.user.credits.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update your account email address # -# PUT /user/email # - -data = { - "email": "example@example.com" -} -response = sg.client.user.email.put(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve your account email address # -# GET /user/email # - -response = sg.client.user.email.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update your password # -# PUT /user/password # - -data = { - "new_password": "new_password", - "old_password": "old_password" -} -response = sg.client.user.password.put(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a user's profile # -# PATCH /user/profile # - -data = { - "city": "Orange", - "first_name": "Example", - "last_name": "User" -} -response = sg.client.user.profile.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Get a user's profile # -# GET /user/profile # - -response = sg.client.user.profile.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Cancel or pause a scheduled send # -# POST /user/scheduled_sends # - -data = { - "batch_id": "YOUR_BATCH_ID", - "status": "pause" -} -response = sg.client.user.scheduled_sends.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all scheduled sends # -# GET /user/scheduled_sends # - -response = sg.client.user.scheduled_sends.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update user scheduled send information # -# PATCH /user/scheduled_sends/{batch_id} # - -data = { - "status": "pause" -} -batch_id = "test_url_param" -response = sg.client.user.scheduled_sends._(batch_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve scheduled send # -# GET /user/scheduled_sends/{batch_id} # - -batch_id = "test_url_param" -response = sg.client.user.scheduled_sends._(batch_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a cancellation or pause of a scheduled send # -# DELETE /user/scheduled_sends/{batch_id} # - -batch_id = "test_url_param" -response = sg.client.user.scheduled_sends._(batch_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update Enforced TLS settings # -# PATCH /user/settings/enforced_tls # - -data = { - "require_tls": True, - "require_valid_cert": False -} -response = sg.client.user.settings.enforced_tls.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve current Enforced TLS settings. # -# GET /user/settings/enforced_tls # - -response = sg.client.user.settings.enforced_tls.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update your username # -# PUT /user/username # - -data = { - "username": "test_username" -} -response = sg.client.user.username.put(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve your username # -# GET /user/username # - -response = sg.client.user.username.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update Event Notification Settings # -# PATCH /user/webhooks/event/settings # - -data = { - "bounce": True, - "click": True, - "deferred": True, - "delivered": True, - "dropped": True, - "enabled": True, - "group_resubscribe": True, - "group_unsubscribe": True, - "open": True, - "processed": True, - "spam_report": True, - "unsubscribe": True, - "url": "url" -} -response = sg.client.user.webhooks.event.settings.patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve Event Webhook settings # -# GET /user/webhooks/event/settings # - -response = sg.client.user.webhooks.event.settings.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Test Event Notification Settings # -# POST /user/webhooks/event/test # - -data = { - "url": "url" -} -response = sg.client.user.webhooks.event.test.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Create a parse setting # -# POST /user/webhooks/parse/settings # - -data = { - "hostname": "myhostname.com", - "send_raw": False, - "spam_check": True, - "url": "http://email.myhosthame.com" -} -response = sg.client.user.webhooks.parse.settings.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all parse settings # -# GET /user/webhooks/parse/settings # - -response = sg.client.user.webhooks.parse.settings.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a parse setting # -# PATCH /user/webhooks/parse/settings/{hostname} # - -data = { - "send_raw": True, - "spam_check": False, - "url": "http://newdomain.com/parse" -} -hostname = "test_url_param" -response = sg.client.user.webhooks.parse.settings._(hostname).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a specific parse setting # -# GET /user/webhooks/parse/settings/{hostname} # - -hostname = "test_url_param" -response = sg.client.user.webhooks.parse.settings._(hostname).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a parse setting # -# DELETE /user/webhooks/parse/settings/{hostname} # - -hostname = "test_url_param" -response = sg.client.user.webhooks.parse.settings._(hostname).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieves Inbound Parse Webhook statistics. # -# GET /user/webhooks/parse/stats # - -params = {'aggregated_by': 'day', 'limit': 'test_string', 'start_date': '2016-01-01', 'end_date': '2016-04-01', 'offset': 'test_string'} -response = sg.client.user.webhooks.parse.stats.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - diff --git a/docker/examples/whitelabel/whitelabel.py b/docker/examples/whitelabel/whitelabel.py deleted file mode 100644 index f529d3ed2..000000000 --- a/docker/examples/whitelabel/whitelabel.py +++ /dev/null @@ -1,311 +0,0 @@ -import sendgrid -import json -import os - - -sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) - -################################################## -# Create a domain whitelabel. # -# POST /whitelabel/domains # - -data = { - "automatic_security": False, - "custom_spf": True, - "default": True, - "domain": "example.com", - "ips": [ - "192.168.1.1", - "192.168.1.2" - ], - "subdomain": "news", - "username": "john@example.com" -} -response = sg.client.whitelabel.domains.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# List all domain whitelabels. # -# GET /whitelabel/domains # - -params = {'username': 'test_string', 'domain': 'test_string', 'exclude_subusers': 'true', 'limit': 1, 'offset': 1} -response = sg.client.whitelabel.domains.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Get the default domain whitelabel. # -# GET /whitelabel/domains/default # - -response = sg.client.whitelabel.domains.default.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# List the domain whitelabel associated with the given user. # -# GET /whitelabel/domains/subuser # - -response = sg.client.whitelabel.domains.subuser.get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Disassociate a domain whitelabel from a given user. # -# DELETE /whitelabel/domains/subuser # - -response = sg.client.whitelabel.domains.subuser.delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a domain whitelabel. # -# PATCH /whitelabel/domains/{domain_id} # - -data = { - "custom_spf": True, - "default": False -} -domain_id = "test_url_param" -response = sg.client.whitelabel.domains._(domain_id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a domain whitelabel. # -# GET /whitelabel/domains/{domain_id} # - -domain_id = "test_url_param" -response = sg.client.whitelabel.domains._(domain_id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a domain whitelabel. # -# DELETE /whitelabel/domains/{domain_id} # - -domain_id = "test_url_param" -response = sg.client.whitelabel.domains._(domain_id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Associate a domain whitelabel with a given user. # -# POST /whitelabel/domains/{domain_id}/subuser # - -data = { - "username": "jane@example.com" -} -domain_id = "test_url_param" -response = sg.client.whitelabel.domains._(domain_id).subuser.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Add an IP to a domain whitelabel. # -# POST /whitelabel/domains/{id}/ips # - -data = { - "ip": "192.168.0.1" -} -id = "test_url_param" -response = sg.client.whitelabel.domains._(id).ips.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Remove an IP from a domain whitelabel. # -# DELETE /whitelabel/domains/{id}/ips/{ip} # - -id = "test_url_param" -ip = "test_url_param" -response = sg.client.whitelabel.domains._(id).ips._(ip).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Validate a domain whitelabel. # -# POST /whitelabel/domains/{id}/validate # - -id = "test_url_param" -response = sg.client.whitelabel.domains._(id).validate.post() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Create an IP whitelabel # -# POST /whitelabel/ips # - -data = { - "domain": "example.com", - "ip": "192.168.1.1", - "subdomain": "email" -} -response = sg.client.whitelabel.ips.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all IP whitelabels # -# GET /whitelabel/ips # - -params = {'ip': 'test_string', 'limit': 1, 'offset': 1} -response = sg.client.whitelabel.ips.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve an IP whitelabel # -# GET /whitelabel/ips/{id} # - -id = "test_url_param" -response = sg.client.whitelabel.ips._(id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete an IP whitelabel # -# DELETE /whitelabel/ips/{id} # - -id = "test_url_param" -response = sg.client.whitelabel.ips._(id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Validate an IP whitelabel # -# POST /whitelabel/ips/{id}/validate # - -id = "test_url_param" -response = sg.client.whitelabel.ips._(id).validate.post() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Create a Link Whitelabel # -# POST /whitelabel/links # - -data = { - "default": True, - "domain": "example.com", - "subdomain": "mail" -} -params = {'limit': 1, 'offset': 1} -response = sg.client.whitelabel.links.post(request_body=data, query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve all link whitelabels # -# GET /whitelabel/links # - -params = {'limit': 1} -response = sg.client.whitelabel.links.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a Default Link Whitelabel # -# GET /whitelabel/links/default # - -params = {'domain': 'test_string'} -response = sg.client.whitelabel.links.default.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve Associated Link Whitelabel # -# GET /whitelabel/links/subuser # - -params = {'username': 'test_string'} -response = sg.client.whitelabel.links.subuser.get(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Disassociate a Link Whitelabel # -# DELETE /whitelabel/links/subuser # - -params = {'username': 'test_string'} -response = sg.client.whitelabel.links.subuser.delete(query_params=params) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Update a Link Whitelabel # -# PATCH /whitelabel/links/{id} # - -data = { - "default": True -} -id = "test_url_param" -response = sg.client.whitelabel.links._(id).patch(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Retrieve a Link Whitelabel # -# GET /whitelabel/links/{id} # - -id = "test_url_param" -response = sg.client.whitelabel.links._(id).get() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Delete a Link Whitelabel # -# DELETE /whitelabel/links/{id} # - -id = "test_url_param" -response = sg.client.whitelabel.links._(id).delete() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Validate a Link Whitelabel # -# POST /whitelabel/links/{id}/validate # - -id = "test_url_param" -response = sg.client.whitelabel.links._(id).validate.post() -print(response.status_code) -print(response.body) -print(response.headers) - -################################################## -# Associate a Link Whitelabel # -# POST /whitelabel/links/{link_id}/subuser # - -data = { - "username": "jane@example.com" -} -link_id = "test_url_param" -response = sg.client.whitelabel.links._(link_id).subuser.post(request_body=data) -print(response.status_code) -print(response.body) -print(response.headers) - From 220d2c369541319c45aa08fbd3309054d5a21e8d Mon Sep 17 00:00:00 2001 From: Bhargav Chandaka Date: Sun, 8 Jul 2018 18:57:21 -0500 Subject: [PATCH 20/45] Update Readme Added windows environment variable setup --- README.md | 228 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..0b6a3b483 --- /dev/null +++ b/README.md @@ -0,0 +1,228 @@ +![SendGrid Logo](https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png) + +[![Travis Badge](https://travis-ci.org/sendgrid/sendgrid-python.svg?branch=master)](https://travis-ci.org/sendgrid/sendgrid-python) +[![codecov](https://img.shields.io/codecov/c/github/sendgrid/sendgrid-python/master.svg?style=flat-square&label=Codecov+Coverage)](https://codecov.io/gh/sendgrid/sendgrid-python) +[![Docker Badge](https://img.shields.io/docker/automated/sendgrid/sendgrid-python.svg)](https://hub.docker.com/r/sendgrid/sendgrid-python/) +[![Email Notifications Badge](https://dx.sendgrid.com/badge/python)](https://dx.sendgrid.com/newsletter/python) +[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.txt) +[![Twitter Follow](https://img.shields.io/twitter/follow/sendgrid.svg?style=social&label=Follow)](https://twitter.com/sendgrid) +[![GitHub contributors](https://img.shields.io/github/contributors/sendgrid/sendgrid-python.svg)](https://github.com/sendgrid/sendgrid-python/graphs/contributors) + +**NEW:** + +* Subscribe to email [notifications](https://dx.sendgrid.com/newsletter/python) for releases and breaking changes. +* Quickly get started with [Docker](https://github.com/sendgrid/sendgrid-python/tree/master/docker). + +**This library allows you to quickly and easily use the SendGrid Web API v3 via Python.** + +Version 3.X.X+ of this library provides full support for all SendGrid [Web API v3](https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html) endpoints, including the new [v3 /mail/send](https://sendgrid.com/blog/introducing-v3mailsend-sendgrids-new-mail-endpoint). + +This library represents the beginning of a new path for SendGrid. We want this library to be community driven and SendGrid led. We need your help to realize this goal. To help make sure we are building the right things in the right order, we ask that you create [issues](https://github.com/sendgrid/sendgrid-python/issues) and [pull requests](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md) or simply upvote or comment on existing issues or pull requests. + +Please browse the rest of this README for further detail. + +We appreciate your continued support, thank you! + +# Table of Contents + +* [Installation](#installation) +* [Quick Start](#quick-start) +* [Processing Inbound Email](#inbound) +* [Usage](#usage) +* [Use Cases](#use-cases) +* [Announcements](#announcements) +* [Roadmap](#roadmap) +* [How to Contribute](#contribute) +* [Troubleshooting](#troubleshooting) +* [About](#about) +* [License](#license) + + +# Installation + +## Prerequisites + +- Python version 2.6, 2.7, 3.4, 3.5 or 3.6 +- The SendGrid service, starting at the [free level](https://sendgrid.com/free?source=sendgrid-python) + +## Setup Environment Variables +Update the development environment with your [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys), for example: +### Mac +```bash +echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env +echo "sendgrid.env" >> .gitignore +source ./sendgrid.env +``` +Sendgrid also supports local environment file `.env`. Copy or rename `.env_sample` into `.env` and update [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys) with your key. + +### Windows +Temporarily set the environment variable(accesible only during the current cli session): +```bash +set SENDGRID_API_KEY=YOUR_API_KEY +``` +Permanently set the environment variable: +```bash +setx SENDGRID_API_KEY "YOUR_API_KEY" +``` + +## Install Package +```bash +pip install sendgrid +``` + +## Dependencies + +- [Python-HTTP-Client](https://github.com/sendgrid/python-http-client) + + +# Quick Start + +## Hello Email + +The following is the minimum needed code to send an email with the [/mail/send Helper](https://github.com/sendgrid/sendgrid-python/tree/master/sendgrid/helpers/mail) ([here](https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail/mail_example.py#L20) is a full example): + +### With Mail Helper Class + +```python +import sendgrid +import os +from sendgrid.helpers.mail import * + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) +from_email = Email("test@example.com") +to_email = Email("test@example.com") +subject = "Sending with SendGrid is Fun" +content = Content("text/plain", "and easy to do anywhere, even with Python") +mail = Mail(from_email, subject, to_email, content) +response = sg.client.mail.send.post(request_body=mail.get()) +print(response.status_code) +print(response.body) +print(response.headers) +``` + +The `Mail` constructor creates a [personalization object](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html) for you. [Here](https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail/mail_example.py#L16) is an example of how to add it. + +### Without Mail Helper Class + +The following is the minimum needed code to send an email without the /mail/send Helper ([here](https://github.com/sendgrid/sendgrid-python/blob/master/examples/mail/mail.py#L27) is a full example): + +```python +import sendgrid +import os + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) +data = { + "personalizations": [ + { + "to": [ + { + "email": "test@example.com" + } + ], + "subject": "Sending with SendGrid is Fun" + } + ], + "from": { + "email": "test@example.com" + }, + "content": [ + { + "type": "text/plain", + "value": "and easy to do anywhere, even with Python" + } + ] +} +response = sg.client.mail.send.post(request_body=data) +print(response.status_code) +print(response.body) +print(response.headers) +``` + +## General v3 Web API Usage (With [Fluent Interface](https://sendgrid.com/blog/using-python-to-implement-a-fluent-interface-to-any-rest-api/)) + +```python +import sendgrid +import os + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) +response = sg.client.suppression.bounces.get() +print(response.status_code) +print(response.body) +print(response.headers) +``` + +## General v3 Web API Usage (Without Fluent Interface) + +```python +import sendgrid +import os + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) +response = sg.client._("suppression/bounces").get() +print(response.status_code) +print(response.body) +print(response.headers) +``` + + +# Processing Inbound Email + +Please see [our helper](https://github.com/sendgrid/sendgrid-python/tree/master/sendgrid/helpers/inbound) for utilizing our Inbound Parse webhook. + + +# Usage + +- [SendGrid Documentation](https://sendgrid.com/docs/API_Reference/index.html) +- [Library Usage Documentation](https://github.com/sendgrid/sendgrid-python/tree/master/USAGE.md) +- [Example Code](https://github.com/sendgrid/sendgrid-python/tree/master/examples) +- [How-to: Migration from v2 to v3](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/how_to_migrate_from_v2_to_v3_mail_send.html) +- [v3 Web API Mail Send Helper](https://github.com/sendgrid/sendgrid-python/tree/master/sendgrid/helpers/mail) - build a request object payload for a v3 /mail/send API call. +- [Processing Inbound Email](https://github.com/sendgrid/sendgrid-python/tree/master/sendgrid/helpers/inbound) + + +# Use Cases + +[Examples of common API use cases](https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/README.md), such as how to send an email with a transactional template. + + +# Announcements + +Join an experienced and passionate team that focuses on making an impact. Opportunities abound to grow the product - and grow your career! Check out our [Data Platform Engineer role](http://grnh.se/wbx1701) + +Please see our announcement regarding [breaking changes](https://github.com/sendgrid/sendgrid-python/issues/217). Your support is appreciated! + +All updates to this library are documented in our [CHANGELOG](https://github.com/sendgrid/sendgrid-python/blob/master/CHANGELOG.md) and [releases](https://github.com/sendgrid/sendgrid-python/releases). You may also subscribe to email [release notifications](https://dx.sendgrid.com/newsletter/java) for releases and breaking changes. + + +# Roadmap + +If you are interested in the future direction of this project, please take a look at our open [issues](https://github.com/sendgrid/sendgrid-python/issues) and [pull requests](https://github.com/sendgrid/sendgrid-python/pulls). We would love to hear your feedback. + + +# How to Contribute + +We encourage contribution to our libraries (you might even score some nifty swag), please see our [CONTRIBUTING](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md) guide for details. + +Quick links: + +- [Feature Request](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md#feature-request) +- [Bug Reports](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md#submit-a-bug-report) +- [Sign the CLA to Create a Pull Request](https://cla.sendgrid.com/sendgrid/sendgrid-python) +- [Improvements to the Codebase](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md#improvements-to-the-codebase) +- [Review Pull Requests](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md#code-reviews) + + +# Troubleshooting + +Please see our [troubleshooting guide](https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md) for common library issues. + + +# About + +sendgrid-python is guided and supported by the SendGrid [Developer Experience Team](mailto:dx@sendgrid.com). + +sendgrid-python is maintained and funded by SendGrid, Inc. The names and logos for sendgrid-python are trademarks of SendGrid, Inc. + + +# License +[The MIT License (MIT)](LICENSE.txt) From 55b1818f855ba2e4dd3a4e41a158830ad8918777 Mon Sep 17 00:00:00 2001 From: Bhargav Chandaka Date: Sun, 8 Jul 2018 18:59:56 -0500 Subject: [PATCH 21/45] Update README.md Added environmental variable setup in windows --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0b6a3b483..f34a46235 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ Temporarily set the environment variable(accesible only during the current cli s ```bash set SENDGRID_API_KEY=YOUR_API_KEY ``` -Permanently set the environment variable: +Permanently set the environment variable(accessible in all subsequent cli sessions): ```bash setx SENDGRID_API_KEY "YOUR_API_KEY" ``` From bb5c5c012cefca78bc97327da6b8a6323456fc6d Mon Sep 17 00:00:00 2001 From: Swapnil Agarwal Date: Fri, 27 Oct 2017 00:42:03 +0530 Subject: [PATCH 22/45] Add a tutorial to deploy a simple 'Hello Email' app on Heroku See #356 --- use_cases/README.md | 1 + use_cases/flask_heroku.md | 9 +++++++++ 2 files changed, 10 insertions(+) create mode 100644 use_cases/flask_heroku.md diff --git a/use_cases/README.md b/use_cases/README.md index 188464d09..4e0fc24d6 100644 --- a/use_cases/README.md +++ b/use_cases/README.md @@ -8,6 +8,7 @@ This directory provides examples for specific use cases of this library. Please * [How to Create a Django app, Deployed on Heroku, to Send Email with SendGrid](django.md) * [How to Deploy A Simple Hello Email App on AWS](aws.md) +* [How to Deploy a simple Flask app, to send Email with SendGrid, on Heroku](flask_heroku.md) * [How to Setup a Domain Whitelabel](domain_whitelabel.md) * [How to View Email Statistics](email_stats.md) diff --git a/use_cases/flask_heroku.md b/use_cases/flask_heroku.md new file mode 100644 index 000000000..ef0fa599a --- /dev/null +++ b/use_cases/flask_heroku.md @@ -0,0 +1,9 @@ +# Create a Flask app to send email with SendGrid + +This tutorial explains how to deploy a simple Flask app, to send an email using the SendGrid Python SDK, on Heroku. + +1. Create a SendGrid API key at https://app.sendgrid.com/settings/api_keys +1. Go to https://github.com/swapagarwal/sendgrid-flask-heroku +1. Click on `Deploy to Heroku` button, and follow the instructions. + +That's all. You'll be sending your first email within seconds! From 3066939ac5b466b17f192137dae659e34daffe4b Mon Sep 17 00:00:00 2001 From: Slam <3lnc.slam@gmail.com> Date: Wed, 1 Aug 2018 20:16:35 +0300 Subject: [PATCH 23/45] Adds support for dynamic template data in personalizations --- examples/helpers/{mail => }/mail_example.py | 26 +++++++++++++++++---- sendgrid/helpers/mail/personalization.py | 5 ++++ test/test_mail.py | 11 +++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) rename examples/helpers/{mail => }/mail_example.py (91%) diff --git a/examples/helpers/mail/mail_example.py b/examples/helpers/mail_example.py similarity index 91% rename from examples/helpers/mail/mail_example.py rename to examples/helpers/mail_example.py index b2de7f0a0..e227b22cc 100644 --- a/examples/helpers/mail/mail_example.py +++ b/examples/helpers/mail_example.py @@ -1,8 +1,6 @@ -import json -import os -import urllib2 +from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import * -from sendgrid import * + # NOTE: you will need move this file to the root # directory of this project to execute properly. @@ -217,3 +215,23 @@ def send_kitchen_sink(): # this will only send an email if you set SandBox Mode to False send_kitchen_sink() + + +def dynamic_template_usage(): + """ + Sample usage of dynamic (handlebars) transactional templates. + To make this work, you should have dynamic template created within your + SendGrid account. For this particular example, template may be like:: + +

Hello, {{name}}! Your current balance is {{balance}}

+ + """ + mail = Mail(from_email='templates@sendgrid.com') + mail.template_id = 'd-your-dynamic-template-uid' + p = Personalization() + p.add_to(Email('user@example.com')) + p.dynamic_template_data = {'name': 'Bob', 'balance': 42} + mail.add_personalization(p) + + sg = SendGridAPIClient(apikey='SG.your-api-key') + sg.client.mail.send.post(request_body=mail.get()) diff --git a/sendgrid/helpers/mail/personalization.py b/sendgrid/helpers/mail/personalization.py index 49a779cf9..60e353924 100644 --- a/sendgrid/helpers/mail/personalization.py +++ b/sendgrid/helpers/mail/personalization.py @@ -1,6 +1,10 @@ class Personalization(object): """A Personalization defines who should receive an individual message and how that message should be handled. + + :var dynamic_template_data: data for dynamic transactional template. + Should be JSON-serializeable structure. No pre-processing sill be done + prior to sending this via http client. """ def __init__(self): @@ -13,6 +17,7 @@ def __init__(self): self._substitutions = [] self._custom_args = [] self._send_at = None + self.dynamic_template_data = None @property def tos(self): diff --git a/test/test_mail.py b/test/test_mail.py index 98af29a09..c9b4d0d30 100644 --- a/test/test_mail.py +++ b/test/test_mail.py @@ -557,3 +557,14 @@ def test_disable_tracking(self): def test_directly_setting_substitutions(self): personalization = Personalization() personalization.substitutions = [{'a': 0}] + + def test_dynamic_template_data(self): + p = Personalization() + p.add_to(Email('test@sendgrid.com')) + p.dynamic_template_data = {'customer': {'name': 'Bob', 'returning': True}, 'total': 42} + + expected = { + 'to': [{'email': 'test@sendgrid.com'}], + 'dynamic_template_data': {'customer': {'name': 'Bob', 'returning': True}, 'total': 42} + } + self.assertDictEqual(p.get(), expected) From 6aeea8a5e76a122f785aaa662f731dcc3aaf506f Mon Sep 17 00:00:00 2001 From: Slam <3lnc.slam@gmail.com> Date: Wed, 1 Aug 2018 20:30:30 +0300 Subject: [PATCH 24/45] Example for .md usecase --- use_cases/transational_templates.md | 32 ++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/use_cases/transational_templates.md b/use_cases/transational_templates.md index d3e3a005d..1e89e08a9 100644 --- a/use_cases/transational_templates.md +++ b/use_cases/transational_templates.md @@ -66,6 +66,36 @@ print(response.body) print(response.headers) ``` +### With dynamic templates + +Sendgrid dynamic templates let you leverage power of [handlebars](https://handlebarsjs.com/) +syntax to easily manage complex dynamic content in transactional emails. + +To check this example snippet, create transactional email with code like +```html +

Hello, {{name}}! Your current balance is {{balance}}

+``` + +Than send email based on it, providing context for substitutions: +```python +from sendgrid import SendGridAPIClient +from sendgrid.helpers.mail import Email, Personalization + + +sg = SendGridAPIClient(apikey='SG.your-api-key') + +mail = Mail(from_email='templates@example.com') +mail.template_id = 'd-your-dynamic-template-uid' +p = Personalization() +p.add_to(Email('user@example.com')) +p.dynamic_template_data = {'name': 'Bob', 'balance': 42} +mail.add_personalization(p) + +sg.client.mail.send.post(request_body=mail.get()) +``` + +Read more about dynamic templates in [docs](https://sendgrid.com/docs/User_Guide/Transactional_Templates/how_to_send_an_email_with_transactional_templates.html) + ## Without Mail Helper Class ```python @@ -113,4 +143,4 @@ except urllib.HTTPError as e: print(response.status_code) print(response.body) print(response.headers) -``` \ No newline at end of file +``` From 9d3fe35e776d51da02018d6b81efa57ea40b3be9 Mon Sep 17 00:00:00 2001 From: Slam <3lnc.slam@gmail.com> Date: Wed, 1 Aug 2018 20:35:15 +0300 Subject: [PATCH 25/45] Linking SG dashboard --- use_cases/transational_templates.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/use_cases/transational_templates.md b/use_cases/transational_templates.md index 1e89e08a9..d88ffae76 100644 --- a/use_cases/transational_templates.md +++ b/use_cases/transational_templates.md @@ -71,7 +71,8 @@ print(response.headers) Sendgrid dynamic templates let you leverage power of [handlebars](https://handlebarsjs.com/) syntax to easily manage complex dynamic content in transactional emails. -To check this example snippet, create transactional email with code like +To check this example snippet, create +[transactional email template](https://sendgrid.com/dynamic_templates) with code like ```html

Hello, {{name}}! Your current balance is {{balance}}

``` From fa8d598339087c350699103460b8a65d3b875c8b Mon Sep 17 00:00:00 2001 From: lifez Date: Fri, 3 Aug 2018 18:18:34 +0700 Subject: [PATCH 26/45] Install pip for python3.6 --- docker/Dockerfile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 9de0928a1..31775cfa7 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -28,14 +28,15 @@ RUN chmod +x ./install.sh && sync && \ # install pip, tox ADD https://bootstrap.pypa.io/get-pip.py get-pip.py RUN python2.7 get-pip.py && \ + python3.6 get-pip.py && \ pip install tox && \ rm get-pip.py #install pyyaml, six, werkzeug RUN python3.6 -m pip install pyyaml RUN python3.6 -m pip install six -RUN Python3.6 -m pip install werkzeug -RUN Python3.6 -m pip install flask +RUN python3.6 -m pip install werkzeug +RUN python3.6 -m pip install flask # set up default sendgrid env WORKDIR /root/sources From cfe316aa17e1736891496b8616878223a4204821 Mon Sep 17 00:00:00 2001 From: Ryan Jarvis Date: Fri, 3 Aug 2018 16:30:39 -0700 Subject: [PATCH 27/45] Update TROUBLESHOOTING.md --- TROUBLESHOOTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md index 29c0c8e89..331aee8e7 100644 --- a/TROUBLESHOOTING.md +++ b/TROUBLESHOOTING.md @@ -50,7 +50,7 @@ import urllib try: response = sg.client.mail.send.post(request_body=mail.get()) except urllib.error.HTTPError as e: - print e.read() + print(e.read()) ``` From d6c85415f3f7f10cbb5d881bdca96cb021fb6fa0 Mon Sep 17 00:00:00 2001 From: Anshul Singhal Date: Mon, 6 Aug 2018 13:05:57 -0700 Subject: [PATCH 28/45] Updated README for more info --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f34a46235..ea9754520 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ We appreciate your continued support, thank you! * [License](#license) + # Installation ## Prerequisites @@ -74,6 +75,7 @@ pip install sendgrid - [Python-HTTP-Client](https://github.com/sendgrid/python-http-client) + # Quick Start From 7e9d5c560f35405054dad1931cda1ca468665bcb Mon Sep 17 00:00:00 2001 From: Anshul Singhal Date: Tue, 7 Aug 2018 11:27:00 -0700 Subject: [PATCH 29/45] readme tag update --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ea9754520..20d243d14 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.txt) [![Twitter Follow](https://img.shields.io/twitter/follow/sendgrid.svg?style=social&label=Follow)](https://twitter.com/sendgrid) [![GitHub contributors](https://img.shields.io/github/contributors/sendgrid/sendgrid-python.svg)](https://github.com/sendgrid/sendgrid-python/graphs/contributors) +[![Open Source Helpers](https://www.codetriage.com/sendgrid/sendgrid-python/badges/users.svg)](https://www.codetriage.com/sendgrid/sendgrid-python) **NEW:** From 66cc616e2696dc3bf5d20dba242b2eba3b3fa1b3 Mon Sep 17 00:00:00 2001 From: af4ro <1997anshul@gmail.com> Date: Thu, 9 Aug 2018 09:39:27 -0700 Subject: [PATCH 30/45] minor formatting --- examples/helpers/mail_example.py | 8 ++++++-- test/test_mail.py | 16 ++++++++++++++-- use_cases/transational_templates.md | 3 ++- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/examples/helpers/mail_example.py b/examples/helpers/mail_example.py index e227b22cc..0a5b868bc 100644 --- a/examples/helpers/mail_example.py +++ b/examples/helpers/mail_example.py @@ -226,11 +226,15 @@ def dynamic_template_usage():

Hello, {{name}}! Your current balance is {{balance}}

""" - mail = Mail(from_email='templates@sendgrid.com') + mail = Mail() + mail.from_email = 'templates@sendgrid.com' mail.template_id = 'd-your-dynamic-template-uid' p = Personalization() p.add_to(Email('user@example.com')) - p.dynamic_template_data = {'name': 'Bob', 'balance': 42} + p.dynamic_template_data = { + 'name': 'Bob', + 'balance': 42 + } mail.add_personalization(p) sg = SendGridAPIClient(apikey='SG.your-api-key') diff --git a/test/test_mail.py b/test/test_mail.py index c9b4d0d30..0c0b668a2 100644 --- a/test/test_mail.py +++ b/test/test_mail.py @@ -561,10 +561,22 @@ def test_directly_setting_substitutions(self): def test_dynamic_template_data(self): p = Personalization() p.add_to(Email('test@sendgrid.com')) - p.dynamic_template_data = {'customer': {'name': 'Bob', 'returning': True}, 'total': 42} + p.dynamic_template_data = { + 'customer': { + 'name': 'Bob', + 'returning': True + }, + 'total': 42 + } expected = { 'to': [{'email': 'test@sendgrid.com'}], - 'dynamic_template_data': {'customer': {'name': 'Bob', 'returning': True}, 'total': 42} + 'dynamic_template_data': { + 'customer': { + 'name': 'Bob', + 'returning': True + }, + 'total': 42 + } } self.assertDictEqual(p.get(), expected) diff --git a/use_cases/transational_templates.md b/use_cases/transational_templates.md index d88ffae76..2d74f92a5 100644 --- a/use_cases/transational_templates.md +++ b/use_cases/transational_templates.md @@ -85,7 +85,8 @@ from sendgrid.helpers.mail import Email, Personalization sg = SendGridAPIClient(apikey='SG.your-api-key') -mail = Mail(from_email='templates@example.com') +mail = Mail() +mail.from_email='templates@example.com' mail.template_id = 'd-your-dynamic-template-uid' p = Personalization() p.add_to(Email('user@example.com')) From 02de2b2dba6bc254db14eca1a5cabf4c794f05b1 Mon Sep 17 00:00:00 2001 From: Anshul Singhal <1997anshul@gmail.com> Date: Fri, 10 Aug 2018 16:03:54 -0700 Subject: [PATCH 31/45] Minor readability update --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c4aa2c4a5..f46bf97d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -184,8 +184,10 @@ Please run your code through: ```bash # Clone your fork of the repo into the current directory git clone https://github.com/sendgrid/sendgrid-python + # Navigate to the newly cloned directory cd sendgrid-python + # Assign the original repo to a remote called "upstream" git remote add upstream https://github.com/sendgrid/sendgrid-python ``` From c360b7c459526f35a6cf8c96853066e5d49c2c76 Mon Sep 17 00:00:00 2001 From: Navin Pai Date: Tue, 14 Aug 2018 03:00:04 +0530 Subject: [PATCH 32/45] Add slack API integration to use_cases --- use_cases/README.md | 1 + use_cases/slack_event_api_integration.md | 46 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 use_cases/slack_event_api_integration.md diff --git a/use_cases/README.md b/use_cases/README.md index 4e0fc24d6..9966616e5 100644 --- a/use_cases/README.md +++ b/use_cases/README.md @@ -16,6 +16,7 @@ This directory provides examples for specific use cases of this library. Please * [Asynchronous Mail Send](asynchronous_mail_send.md) * [Attachment](attachment.md) * [Transactional Templates](transational_templates.md) +* [Integrate with Slack Events API](slack_event_api_integration.md) ### Library Features * [Error Handling](error_handling.md) \ No newline at end of file diff --git a/use_cases/slack_event_api_integration.md b/use_cases/slack_event_api_integration.md new file mode 100644 index 000000000..d0e0f6140 --- /dev/null +++ b/use_cases/slack_event_api_integration.md @@ -0,0 +1,46 @@ +# Integrate with Slack Events API + +It's fairly straightforward to integrate Sendgrid with Slack, to allow emails to be triggered by events happening on Slack. + +For this, we make use of the [Official Slack Events API](https://github.com/slackapi/python-slack-events-api), which can be installed using pip. + +To allow our application to get notifications of slack events, we first create a Slack App with Event Subscriptions as described [here](https://github.com/slackapi/python-slack-events-api#--development-workflow) + +Then, we set `SENDGRID_API_KEY` _(which you can create on the Sendgrid dashboard)_ and `SLACK_VERIFICATION_TOKEN` _(which you can get in the App Credentials section of the Slack App)_ as environment variables. + +Once this is done, we can subscribe to [events on Slack](https://api.slack.com/events) and trigger emails when an event occurs. In the example below, we trigger an email to `test@example.com` whenever someone posts a message on Slack that has the word "_help_" in it. + +``` +from slackeventsapi import SlackEventAdapter +from slackclient import SlackClient +import os +import sendgrid +from sendgrid.helpers.mail import * + +sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) + +SLACK_VERIFICATION_TOKEN = os.environ["SLACK_VERIFICATION_TOKEN"] +slack_events_adapter = SlackEventAdapter(SLACK_VERIFICATION_TOKEN, "/slack/events") + +@slack_events_adapter.on("message") +def handle_message(event_data): + message = event_data["event"] + # If the incoming message contains "help", then send an email using SendGrid + if message.get("subtype") is None and "help" in message.get('text').lower(): + message = "Someone needs your help: \n\n %s" % message["text"] + r = send_email(message) + print(r) + + +def send_email(message): + from_email = Email("slack_integration@example.com") + to_email = Email("test@example.com") + subject = "Psst... Someone needs help!" + content = Content("text/plain", message) + mail = Mail(from_email, subject, to_email, content) + response = sg.client.mail.send.post(request_body=mail.get()) + return response.status_code + +# Start the slack event listener server on port 3000 +slack_events_adapter.start(port=3000) +``` \ No newline at end of file From ed1301706eae34c779cd0654c446e108050c5489 Mon Sep 17 00:00:00 2001 From: James Purpura Date: Mon, 13 Aug 2018 15:01:44 -0700 Subject: [PATCH 33/45] update TROUBLESHOOTING.md editted "our use cases" link --- TROUBLESHOOTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md index 331aee8e7..1298ab7d1 100644 --- a/TROUBLESHOOTING.md +++ b/TROUBLESHOOTING.md @@ -111,4 +111,4 @@ print mail.get() # Error Handling -Please review [our use_cases](https://github.com/sendgrid/sendgrid-python/use_cases/README.md) for examples of error handling. +Please review [our use_cases](https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/README.md#use-cases) for examples of error handling. From 43e615e70803c8b1db654c2a1cd5a60320c9cbfd Mon Sep 17 00:00:00 2001 From: Agnes Jang Date: Tue, 14 Aug 2018 13:45:04 -0700 Subject: [PATCH 34/45] Added comment for attachments to be base64 encoded --- examples/helpers/mail_example.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/helpers/mail_example.py b/examples/helpers/mail_example.py index 0a5b868bc..65176a6ca 100644 --- a/examples/helpers/mail_example.py +++ b/examples/helpers/mail_example.py @@ -78,7 +78,8 @@ def get_mock_personalization_dict(): def build_attachment1(): - """Build attachment mock.""" + """Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content. + Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md""" attachment = Attachment() attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl" "Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12") From 0be36e244bc0c8a4e38979f8e96c7017f0af3f81 Mon Sep 17 00:00:00 2001 From: Elmer Thomas Date: Thu, 16 Aug 2018 09:22:35 -0700 Subject: [PATCH 35/45] Add missing dependencies --- docker-test/entrypoint.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-test/entrypoint.sh b/docker-test/entrypoint.sh index f64d0cccb..abb55b9f2 100644 --- a/docker-test/entrypoint.sh +++ b/docker-test/entrypoint.sh @@ -13,5 +13,5 @@ fi cd sendgrid-python python3.6 setup.py install -pip install pyyaml six werkzeug flask +pip install pyyaml six werkzeug flask python-http-client exec $SHELL From 39aec4601e1685f4bb4da2671e5a9071ec2dc34f Mon Sep 17 00:00:00 2001 From: Elmer Thomas Date: Thu, 16 Aug 2018 12:03:10 -0700 Subject: [PATCH 36/45] Version Bump v5.5.0: Pre-Dynamic Template Roll Up Release --- CHANGELOG.md | 2 +- docker/README.md | 3 ++- sendgrid/version.py | 2 ++ 3 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 sendgrid/version.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 52f1479e4..7f59658f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ All notable changes to this project will be documented in this file. ## [5.4.1] - 2018-06-26 ## ### Fixed - [PR #585](https://github.com/sendgrid/sendgrid-python/pull/585): Fix typo in `mail_example.py`. Big thanks to [Anurag Anand](https://github.com/theanuraganand) for the PR! -- [PR #583](https://github.com/sendgrid/sendgrid-python/pull/585): Fix `Personalization.substitutions` setter. Trying to set substitutions directly rather than with add_substitution was causing an infinite regress. Big thanks to [Richard Nias](https://github.com/richardnias) for the PR! +- [PR #583](https://github.com/sendgrid/sendgrid-python/pull/583): Fix `Personalization.substitutions` setter. Trying to set substitutions directly rather than with add_substitution was causing an infinite regress. Big thanks to [Richard Nias](https://github.com/richardnias) for the PR! ## [5.4.0] - 2018-06-07 ## ### Added diff --git a/docker/README.md b/docker/README.md index a523dc93d..41c235fcc 100644 --- a/docker/README.md +++ b/docker/README.md @@ -1,5 +1,6 @@ # Supported tags and respective `Dockerfile` links - - `v5.4.1`, `latest` [(Dockerfile)](https://github.com/sendgrid/sendgrid-python/blob/master/docker/Dockerfile) + - `v5.5.0`, `latest` [(Dockerfile)](https://github.com/sendgrid/sendgrid-python/blob/master/docker/Dockerfile) + - `v5.4.1` - `v5.4.0` - `v5.3.0` - `v5.2.1` diff --git a/sendgrid/version.py b/sendgrid/version.py new file mode 100644 index 000000000..30415fcbd --- /dev/null +++ b/sendgrid/version.py @@ -0,0 +1,2 @@ +version_info = (5, 5, 0) +__version__ = '.'.join(str(v) for v in version_info) From 0e0644b91a1e83595f90b510fd408dc6e8920de2 Mon Sep 17 00:00:00 2001 From: Elmer Thomas Date: Mon, 20 Aug 2018 17:05:50 -0700 Subject: [PATCH 37/45] Merge #593 --- docker-test/entrypoint.sh | 2 +- examples/helpers/mail_example.py | 14 ++- sendgrid/helpers/mail/mail.py | 1 + sendgrid/helpers/mail/personalization.py | 14 ++- use_cases/transational_templates.md | 103 +++++++++++++++-------- 5 files changed, 93 insertions(+), 41 deletions(-) diff --git a/docker-test/entrypoint.sh b/docker-test/entrypoint.sh index abb55b9f2..6749e8cf3 100644 --- a/docker-test/entrypoint.sh +++ b/docker-test/entrypoint.sh @@ -13,5 +13,5 @@ fi cd sendgrid-python python3.6 setup.py install -pip install pyyaml six werkzeug flask python-http-client +pip install pyyaml six werkzeug flask python-http-client pytest exec $SHELL diff --git a/examples/helpers/mail_example.py b/examples/helpers/mail_example.py index 65176a6ca..c1cd166ad 100644 --- a/examples/helpers/mail_example.py +++ b/examples/helpers/mail_example.py @@ -218,7 +218,10 @@ def send_kitchen_sink(): send_kitchen_sink() -def dynamic_template_usage(): +def transactional_template_usage(): + # Assumes you set your environment variable: + # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key + """ Sample usage of dynamic (handlebars) transactional templates. To make this work, you should have dynamic template created within your @@ -228,7 +231,7 @@ def dynamic_template_usage(): """ mail = Mail() - mail.from_email = 'templates@sendgrid.com' + mail.from_email = Email('templates@sendgrid.com') mail.template_id = 'd-your-dynamic-template-uid' p = Personalization() p.add_to(Email('user@example.com')) @@ -238,5 +241,8 @@ def dynamic_template_usage(): } mail.add_personalization(p) - sg = SendGridAPIClient(apikey='SG.your-api-key') - sg.client.mail.send.post(request_body=mail.get()) + sg = SendGridAPIClient() + response = sg.client.mail.send.post(request_body=mail.get()) + print(response.status_code) + print(response.headers) + print(response.body) diff --git a/sendgrid/helpers/mail/mail.py b/sendgrid/helpers/mail/mail.py index f374e6ad1..7b586ee00 100644 --- a/sendgrid/helpers/mail/mail.py +++ b/sendgrid/helpers/mail/mail.py @@ -1,6 +1,7 @@ """v3/mail/send response body builder""" from .personalization import Personalization from .header import Header +from .email import Email class Mail(object): diff --git a/sendgrid/helpers/mail/personalization.py b/sendgrid/helpers/mail/personalization.py index 60e353924..5bc36c0f2 100644 --- a/sendgrid/helpers/mail/personalization.py +++ b/sendgrid/helpers/mail/personalization.py @@ -17,7 +17,7 @@ def __init__(self): self._substitutions = [] self._custom_args = [] self._send_at = None - self.dynamic_template_data = None + self._dynamic_template_data = None @property def tos(self): @@ -163,6 +163,18 @@ def send_at(self): def send_at(self, value): self._send_at = value + @property + def dynamic_template_data(self): + """Data for dynamic transactional template. + + :rtype: JSON-serializeable structure + """ + return self._dynamic_template_data + + @dynamic_template_data.setter + def dynamic_template_data(self, json): + self._dynamic_template_data = json + def get(self): """ Get a JSON-ready representation of this Personalization. diff --git a/use_cases/transational_templates.md b/use_cases/transational_templates.md index 2d74f92a5..d3d587bc0 100644 --- a/use_cases/transational_templates.md +++ b/use_cases/transational_templates.md @@ -1,6 +1,71 @@ -# Transactional Templates +### Transactional Templates -For this example, we assume you have created a [transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). Following is the template content we used for testing. +Sendgrid transactional templates let you leverage power of [handlebars](https://handlebarsjs.com/) +syntax to easily manage complex dynamic content in transactional emails. + +For this example, we assume you have created a [transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/create_and_edit_transactional_templates.html). Following is the template content we used for testing. + +This example also assumes you [set your environment variable](https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key) with your SendGrid API Key. + +Template ID (replace with your own): + +```text +d-13b8f94fbcae4ec6b75270d6cb59f932 +``` + +Email Subject: + +```text +{{ subject }} +``` + +Template Body: + +```html + + + + + +Hello {{ name }}, +

+I'm glad you are trying out the template feature! +

+I hope you are having a great day in {{ city }} :) +

+ + +``` + +```python +from sendgrid import SendGridAPIClient +from sendgrid.helpers.mail import Mail, Email, Personalization + + +sg = SendGridAPIClient() +mail = Mail() +mail.from_email = Email('templates@example.com') +mail.template_id = 'd-your-dynamic-template-uid' +p = Personalization() +p.add_to(Email('user@example.com')) +p.dynamic_template_data = { + 'subject': 'Dynamic Templates in Python', + 'name': 'Example User', + 'city': 'Denver' +} +mail.add_personalization(p) + +response = sg.client.mail.send.post(request_body=mail.get()) +print(response.status_code) +print(response.headers) +print(response.body) +``` + +Read more about dynamic templates [here](https://sendgrid.com/docs/User_Guide/Transactional_Templates/how_to_send_an_email_with_transactional_templates.html). + +# Legacy Templates + +For this example, we assume you have created a [Legacy Template](https://sendgrid.com/templates). Following is the template content we used for testing. Template ID (replace with your own): @@ -66,38 +131,6 @@ print(response.body) print(response.headers) ``` -### With dynamic templates - -Sendgrid dynamic templates let you leverage power of [handlebars](https://handlebarsjs.com/) -syntax to easily manage complex dynamic content in transactional emails. - -To check this example snippet, create -[transactional email template](https://sendgrid.com/dynamic_templates) with code like -```html -

Hello, {{name}}! Your current balance is {{balance}}

-``` - -Than send email based on it, providing context for substitutions: -```python -from sendgrid import SendGridAPIClient -from sendgrid.helpers.mail import Email, Personalization - - -sg = SendGridAPIClient(apikey='SG.your-api-key') - -mail = Mail() -mail.from_email='templates@example.com' -mail.template_id = 'd-your-dynamic-template-uid' -p = Personalization() -p.add_to(Email('user@example.com')) -p.dynamic_template_data = {'name': 'Bob', 'balance': 42} -mail.add_personalization(p) - -sg.client.mail.send.post(request_body=mail.get()) -``` - -Read more about dynamic templates in [docs](https://sendgrid.com/docs/User_Guide/Transactional_Templates/how_to_send_an_email_with_transactional_templates.html) - ## Without Mail Helper Class ```python @@ -145,4 +178,4 @@ except urllib.HTTPError as e: print(response.status_code) print(response.body) print(response.headers) -``` +``` \ No newline at end of file From 088762ac5be911d248ace4a83d24ab3c80c7c0ef Mon Sep 17 00:00:00 2001 From: Elmer Thomas Date: Mon, 20 Aug 2018 17:12:59 -0700 Subject: [PATCH 38/45] Version Bump v5.6.0: Dynamic Template support --- docker/README.md | 3 ++- sendgrid/version.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docker/README.md b/docker/README.md index 41c235fcc..b439fe892 100644 --- a/docker/README.md +++ b/docker/README.md @@ -1,5 +1,6 @@ # Supported tags and respective `Dockerfile` links - - `v5.5.0`, `latest` [(Dockerfile)](https://github.com/sendgrid/sendgrid-python/blob/master/docker/Dockerfile) + - `v5.6.0`, `latest` [(Dockerfile)](https://github.com/sendgrid/sendgrid-python/blob/master/docker/Dockerfile) + - `v5.5.0` - `v5.4.1` - `v5.4.0` - `v5.3.0` diff --git a/sendgrid/version.py b/sendgrid/version.py index 30415fcbd..fffe2c469 100644 --- a/sendgrid/version.py +++ b/sendgrid/version.py @@ -1,2 +1,2 @@ -version_info = (5, 5, 0) +version_info = (5, 6, 0) __version__ = '.'.join(str(v) for v in version_info) From 1359f0bdf7fdd896814485beb95a40f6a6653dfd Mon Sep 17 00:00:00 2001 From: Elmer Thomas Date: Wed, 22 Aug 2018 13:08:57 -0700 Subject: [PATCH 39/45] Typo in comments --- sendgrid/helpers/mail/personalization.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sendgrid/helpers/mail/personalization.py b/sendgrid/helpers/mail/personalization.py index 5bc36c0f2..125719009 100644 --- a/sendgrid/helpers/mail/personalization.py +++ b/sendgrid/helpers/mail/personalization.py @@ -3,7 +3,7 @@ class Personalization(object): how that message should be handled. :var dynamic_template_data: data for dynamic transactional template. - Should be JSON-serializeable structure. No pre-processing sill be done + Should be JSON-serializeable structure. No pre-processing will be done prior to sending this via http client. """ From d9d2cc1e86604a1d5187436d68ad0d30768f359e Mon Sep 17 00:00:00 2001 From: themousepotato Date: Fri, 28 Sep 2018 09:41:51 +0530 Subject: [PATCH 40/45] fixes #610 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 20d243d14..9e1cac959 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ print(response.body) print(response.headers) ``` -The `Mail` constructor creates a [personalization object](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html) for you. [Here](https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail/mail_example.py#L16) is an example of how to add it. +The `Mail` constructor creates a [personalization object](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html) for you. [Here](https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail_example.py#L16) is an example of how to add it. ### Without Mail Helper Class From d9c585cb23a222680e74d87db2ec3795bd25c04b Mon Sep 17 00:00:00 2001 From: Bharat Raghunathan Date: Mon, 1 Oct 2018 09:41:45 +0530 Subject: [PATCH 41/45] Update README.md by including email Make it clear that the link is a redirect to an email and not to any members page or developer team page --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9e1cac959..4c6d10529 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,8 @@ Please see our [troubleshooting guide](https://github.com/sendgrid/sendgrid-pyth # About -sendgrid-python is guided and supported by the SendGrid [Developer Experience Team](mailto:dx@sendgrid.com). +sendgrid-python is guided and supported by the SendGrid Developer Experience Team. +Email the Developer Experience Team [here](mailto:dx@sendgrid.com) in case of any queries. sendgrid-python is maintained and funded by SendGrid, Inc. The names and logos for sendgrid-python are trademarks of SendGrid, Inc. From 72b85cc594d038af002384985d818d61c5bdc0ce Mon Sep 17 00:00:00 2001 From: Hugo Date: Mon, 1 Oct 2018 11:14:04 +0300 Subject: [PATCH 42/45] Fix typos --- .github/PULL_REQUEST_TEMPLATE | 2 +- CONTRIBUTING.md | 4 ++-- README.md | 6 +++--- sendgrid/__init__.py | 2 +- sendgrid/helpers/endpoints/ip/unassigned.py | 2 +- sendgrid/sendgrid.py | 2 +- use_cases/aws.md | 10 +++++----- use_cases/slack_event_api_integration.md | 4 ++-- use_cases/transational_templates.md | 2 +- 9 files changed, 17 insertions(+), 17 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE index 7ad590b42..b3b7a4446 100644 --- a/.github/PULL_REQUEST_TEMPLATE +++ b/.github/PULL_REQUEST_TEMPLATE @@ -21,4 +21,4 @@ Closes #2 - - -If you have questions, please send an email to [Sendgrid](mailto:dx@sendgrid.com), or file a Github Issue in this repository. +If you have questions, please send an email to [SendGrid](mailto:dx@sendgrid.com), or file a GitHub Issue in this repository. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f46bf97d1..b7d49ba80 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,7 +46,7 @@ A software bug is a demonstrable issue in the code base. In order for us to diag Before you decide to create a new issue, please try the following: -1. Check the Github issues tab if the identified issue has already been reported, if so, please add a +1 to the existing post. +1. Check the GitHub issues tab if the identified issue has already been reported, if so, please add a +1 to the existing post. 2. Update to the latest version of this code and check if issue has already been fixed 3. Copy and fill in the Bug Report Template we have provided below @@ -235,4 +235,4 @@ If you have any additional questions, please feel free to [email](mailto:dx@send ## Code Reviews -If you can, please look at open PRs and review them. Give feedback and help us merge these PRs much faster! If you don't know how, Github has some great [information on how to review a Pull Request](https://help.github.com/articles/about-pull-request-reviews/). +If you can, please look at open PRs and review them. Give feedback and help us merge these PRs much faster! If you don't know how, GitHub has some great [information on how to review a Pull Request](https://help.github.com/articles/about-pull-request-reviews/). diff --git a/README.md b/README.md index 4c6d10529..bca2c50c1 100644 --- a/README.md +++ b/README.md @@ -55,10 +55,10 @@ echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env echo "sendgrid.env" >> .gitignore source ./sendgrid.env ``` -Sendgrid also supports local environment file `.env`. Copy or rename `.env_sample` into `.env` and update [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys) with your key. +SendGrid also supports local environment file `.env`. Copy or rename `.env_sample` into `.env` and update [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys) with your key. -### Windows -Temporarily set the environment variable(accesible only during the current cli session): +### Windows +Temporarily set the environment variable(accessible only during the current cli session): ```bash set SENDGRID_API_KEY=YOUR_API_KEY ``` diff --git a/sendgrid/__init__.py b/sendgrid/__init__.py index 050e798e9..621b3b0d7 100644 --- a/sendgrid/__init__.py +++ b/sendgrid/__init__.py @@ -2,7 +2,7 @@ This library allows you to quickly and easily use the SendGrid Web API v3 via Python. -For more information on this library, see the README on Github. +For more information on this library, see the README on GitHub. https://github.com/sendgrid/sendgrid-python For more information on the SendGrid v3 API, see the v3 docs: http://sendgrid.com/docs/API_Reference/api_v3.html diff --git a/sendgrid/helpers/endpoints/ip/unassigned.py b/sendgrid/helpers/endpoints/ip/unassigned.py index 075f19857..ff5edbd73 100644 --- a/sendgrid/helpers/endpoints/ip/unassigned.py +++ b/sendgrid/helpers/endpoints/ip/unassigned.py @@ -21,7 +21,7 @@ def unassigned(data, as_json=False): and the usernames assigned to an IP unassigned returns a listing of the IP addresses that are allocated - but have 0 usera assigned + but have 0 users assigned data (response.body from sg.client.ips.get()) diff --git a/sendgrid/sendgrid.py b/sendgrid/sendgrid.py index b1665cf61..9a887a845 100644 --- a/sendgrid/sendgrid.py +++ b/sendgrid/sendgrid.py @@ -2,7 +2,7 @@ This library allows you to quickly and easily use the SendGrid Web API v3 via Python. -For more information on this library, see the README on Github. +For more information on this library, see the README on GitHub. https://github.com/sendgrid/sendgrid-python For more information on the SendGrid v3 API, see the v3 docs: http://sendgrid.com/docs/API_Reference/api_v3.html diff --git a/use_cases/aws.md b/use_cases/aws.md index 9c30fd7ed..13a4bbfe3 100644 --- a/use_cases/aws.md +++ b/use_cases/aws.md @@ -13,7 +13,7 @@ Python 2.7 and 3.4 or 3.5 are supported by the sendgrid Python library, however Before starting this tutorial, you will need to have access to an AWS account in which you are allowed to provision resources. This tutorial also assumes you've already created a SendGrid account with free-tier access. Finally, it is highly recommended you utilize [virtualenv](https://virtualenv.pypa.io/en/stable/). -*DISCLAIMER*: Any resources provisioned here may result in charges being incurred to your account. Sendgrid is in no way responsible for any billing charges. +*DISCLAIMER*: Any resources provisioned here may result in charges being incurred to your account. SendGrid is in no way responsible for any billing charges. ## Getting Started @@ -36,15 +36,15 @@ On the next menu, you have the option to choose what programming language you'll Follow the steps on the next screen. Choose a name for your API key, such as "hello-email". Follow the remaining steps to create an environment variable, install the sendgrid module, and copy the test code. Once that is complete, check the "I've integrated the code above" box, and click the "Next: Verify Integration" button. -Assuming all the steps were completed correctly, you should be greeted with a success message. If not, go back and verify that everything is correct, including your API key environment varible, and Python code. +Assuming all the steps were completed correctly, you should be greeted with a success message. If not, go back and verify that everything is correct, including your API key environment variable, and Python code. ## Deploy hello-world app using CodeStar -For the rest of the tutorial, we'll be working out of the git repository we cloned from AWS earlier: +For the rest of the tutorial, we'll be working out of the Git repository we cloned from AWS earlier: ``` $ cd hello-email ``` -note: this assumes you cloned the git repo inside your current directory. My directory is: +note: this assumes you cloned the Git repo inside your current directory. My directory is: ``` ~/projects/hello-email @@ -139,7 +139,7 @@ def handler(event, context): 'headers': {'Content-Type': 'application/json'}} ``` -Note that for the most part, we've simply copied the intial code from the API verification with SendGrid. Some slight modifications were needed to allow it to run as a lambda function, and for the output to be passed cleanly from the API endpoint. +Note that for the most part, we've simply copied the initial code from the API verification with SendGrid. Some slight modifications were needed to allow it to run as a lambda function, and for the output to be passed cleanly from the API endpoint. Change the `test@example.com` emails appropriately so that you may receive the test email. diff --git a/use_cases/slack_event_api_integration.md b/use_cases/slack_event_api_integration.md index d0e0f6140..ecce40695 100644 --- a/use_cases/slack_event_api_integration.md +++ b/use_cases/slack_event_api_integration.md @@ -1,12 +1,12 @@ # Integrate with Slack Events API -It's fairly straightforward to integrate Sendgrid with Slack, to allow emails to be triggered by events happening on Slack. +It's fairly straightforward to integrate SendGrid with Slack, to allow emails to be triggered by events happening on Slack. For this, we make use of the [Official Slack Events API](https://github.com/slackapi/python-slack-events-api), which can be installed using pip. To allow our application to get notifications of slack events, we first create a Slack App with Event Subscriptions as described [here](https://github.com/slackapi/python-slack-events-api#--development-workflow) -Then, we set `SENDGRID_API_KEY` _(which you can create on the Sendgrid dashboard)_ and `SLACK_VERIFICATION_TOKEN` _(which you can get in the App Credentials section of the Slack App)_ as environment variables. +Then, we set `SENDGRID_API_KEY` _(which you can create on the SendGrid dashboard)_ and `SLACK_VERIFICATION_TOKEN` _(which you can get in the App Credentials section of the Slack App)_ as environment variables. Once this is done, we can subscribe to [events on Slack](https://api.slack.com/events) and trigger emails when an event occurs. In the example below, we trigger an email to `test@example.com` whenever someone posts a message on Slack that has the word "_help_" in it. diff --git a/use_cases/transational_templates.md b/use_cases/transational_templates.md index d3d587bc0..491d528bd 100644 --- a/use_cases/transational_templates.md +++ b/use_cases/transational_templates.md @@ -1,6 +1,6 @@ ### Transactional Templates -Sendgrid transactional templates let you leverage power of [handlebars](https://handlebarsjs.com/) +SendGrid transactional templates let you leverage power of [handlebars](https://handlebarsjs.com/) syntax to easily manage complex dynamic content in transactional emails. For this example, we assume you have created a [transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/create_and_edit_transactional_templates.html). Following is the template content we used for testing. From 6982fce080dc01eb82e2007815bed3164f05c85a Mon Sep 17 00:00:00 2001 From: Bharat123Rox Date: Wed, 3 Oct 2018 13:06:39 +0530 Subject: [PATCH 43/45] Update README.md for Email and fix alphabetical order --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bca2c50c1..bc9000b06 100644 --- a/README.md +++ b/README.md @@ -210,9 +210,9 @@ Quick links: - [Feature Request](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md#feature-request) - [Bug Reports](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md#submit-a-bug-report) -- [Sign the CLA to Create a Pull Request](https://cla.sendgrid.com/sendgrid/sendgrid-python) - [Improvements to the Codebase](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md#improvements-to-the-codebase) - [Review Pull Requests](https://github.com/sendgrid/sendgrid-python/blob/master/CONTRIBUTING.md#code-reviews) +- [Sign the CLA to Create a Pull Request](https://cla.sendgrid.com/sendgrid/sendgrid-python) # Troubleshooting From 2893dc7bca20d3885584d2f9a7b20abac189bb2d Mon Sep 17 00:00:00 2001 From: Jeremy Yang Date: Wed, 3 Oct 2018 07:37:24 -0700 Subject: [PATCH 44/45] Update README Remove link to a position not found and replaced with general link to the careers page. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc9000b06..7072b4fd0 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,7 @@ Please see [our helper](https://github.com/sendgrid/sendgrid-python/tree/master/ # Announcements -Join an experienced and passionate team that focuses on making an impact. Opportunities abound to grow the product - and grow your career! Check out our [Data Platform Engineer role](http://grnh.se/wbx1701) +Join an experienced and passionate team that focuses on making an impact. [Opportunities abound](https://sendgrid.com/careers) to grow the product - and grow your career! Please see our announcement regarding [breaking changes](https://github.com/sendgrid/sendgrid-python/issues/217). Your support is appreciated! From 2cc7d4283f489e1990208d790b94bd9b181693ed Mon Sep 17 00:00:00 2001 From: PyroclasticMayhem Date: Thu, 11 Oct 2018 06:50:57 -0400 Subject: [PATCH 45/45] Correct attribution links formating --- CODE_OF_CONDUCT.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 39ed18bf7..2f1c6744f 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -36,6 +36,6 @@ SendGrid thanks the following, on which it draws for content and inspiration: - [Python Community Code of Conduct](https://www.python.org/psf/codeofconduct/) - [Open Source Initiative General Code of Conduct](https://opensource.org/codeofconduct) - [Apache Code of Conduct](https://www.apache.org/foundation/policies/conduct.html) + * [Python Community Code of Conduct](https://www.python.org/psf/codeofconduct/) + * [Open Source Initiative General Code of Conduct](https://opensource.org/codeofconduct) + * [Apache Code of Conduct](https://www.apache.org/foundation/policies/conduct.html)