Skip to content

Commit a836a4c

Browse files
author
Dan
committed
Initial WIP commit - no testing plan yet
1 parent 1ac58c6 commit a836a4c

6 files changed

Lines changed: 208 additions & 6 deletions

File tree

examples/helpers/mail/mail_example.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ def build_personalization(personalization):
3535
for header in personalization['headers']:
3636
mock_personalization.add_header(header)
3737

38-
for substitution in personalization['substitutions']:
39-
mock_personalization.add_substitution(substitution)
38+
for dynamic_template_data in personalization['dynamic_template_data']:
39+
mock_personalization.add_dynamic_template_data(dynamic_template_data)
4040

4141
for arg in personalization['custom_args']:
4242
mock_personalization.add_custom_arg(arg)
@@ -69,8 +69,8 @@ def get_mock_personalization_dict():
6969
mock_pers['headers'] = [Header("X-Test", "test"),
7070
Header("X-Mock", "true")]
7171

72-
mock_pers['substitutions'] = [Substitution("%name%", "Example User"),
73-
Substitution("%city%", "Denver")]
72+
mock_pers['dynamic_template_data'] = [DynamicData("name", "Example User"),
73+
DynamicData("city", "Denver")]
7474

7575
mock_pers['custom_args'] = [CustomArg("user_id", "343"),
7676
CustomArg("type", "marketing")]
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class DynamicData(object):
2+
"""Handlebars compatible dynamic data to be applied to the text and HTML
3+
contents of the body of your email, as well as in the Subject and Reply-To
4+
parameters.
5+
"""
6+
7+
def __init__(self, key=None, value=None):
8+
"""Create DynamicData with the given key and value.
9+
10+
:param key: Text to be replaced with "value" param
11+
:type key: string, optional
12+
:param value: Value to substitute into email
13+
:type value: string or array of objects, optional
14+
"""
15+
self.key = key
16+
self.value = value
17+
18+
@property
19+
def key(self):
20+
return self._key
21+
22+
@key.setter
23+
def key(self, value):
24+
self._key = value
25+
26+
@property
27+
def value(self):
28+
return self._value
29+
30+
@value.setter
31+
def value(self, value):
32+
self._value = value
33+
34+
def get(self):
35+
"""
36+
Get a JSON-ready representation of this DynamicData.
37+
38+
:returns: This DynamicData, ready for use in a request body.
39+
:rtype: dict
40+
"""
41+
dynamic_data = {}
42+
if self.key is not None and self.value is not None:
43+
dynamic_data[self.key] = self.value
44+
return dynamic_data

sendgrid/helpers/mail/personalization.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import warnings
2+
3+
14
class Personalization(object):
25
"""A Personalization defines who should receive an individual message and
36
how that message should be handled.
@@ -10,6 +13,7 @@ def __init__(self):
1013
self._bccs = []
1114
self._subject = None
1215
self._headers = []
16+
self._dynamic_template_data = []
1317
self._substitutions = []
1418
self._custom_args = []
1519
self._send_at = None
@@ -106,6 +110,31 @@ def add_header(self, header):
106110
"""
107111
self._headers.append(header.get())
108112

113+
@property
114+
def dynamic_template_data(self):
115+
"""Dynamic Template Data to be applied within this Personalization.
116+
:rtype: list(dict)
117+
"""
118+
return self._dynamic_template_data
119+
120+
@dynamic_template_data.setter
121+
def dynamic_template_data(self, value):
122+
if len(self.substitutions) > 0:
123+
warnings.warn(
124+
"Dynamic template data should not be used in conjunction with "
125+
"substitutions")
126+
self._dynamic_template_data = value
127+
128+
def add_dynamic_template_data(self, dynamic_template_data):
129+
"""Add a new Substitution to this Personalization.
130+
:type substitution: Substitution
131+
"""
132+
if len(self.substitutions) > 0:
133+
warnings.warn(
134+
"Dynamic template data should not be used in conjunction with "
135+
"substitutions")
136+
self._dynamic_template_data.append(dynamic_template_data.get())
137+
109138
@property
110139
def substitutions(self):
111140
"""Substitutions to be applied within this Personalization.
@@ -116,13 +145,21 @@ def substitutions(self):
116145

117146
@substitutions.setter
118147
def substitutions(self, value):
148+
if len(self.dynamic_template_data) > 0:
149+
warnings.warn(
150+
"Substitutions should not be used in conjunction with "
151+
"dynamic template data")
119152
self._substitutions = value
120153

121154
def add_substitution(self, substitution):
122155
"""Add a new Substitution to this Personalization.
123156
124157
:type substitution: Substitution
125158
"""
159+
if len(self.dynamic_template_data) > 0:
160+
warnings.warn(
161+
"Substitutions should not be used in conjunction with "
162+
"dynamic template data")
126163
self._substitutions.append(substitution.get())
127164

128165
@property
@@ -184,6 +221,12 @@ def get(self):
184221
headers.update(key)
185222
personalization["headers"] = headers
186223

224+
if self.dynamic_template_data:
225+
dynamic_template_data = {}
226+
for key in self.dynamic_template_data:
227+
dynamic_template_data.update(key)
228+
personalization["dynamic_template_data"] = dynamic_template_data
229+
187230
if self.substitutions:
188231
substitutions = {}
189232
for key in self.substitutions:

use_cases/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ This directory provides examples for specific use cases of this library. Please
1414
### Working with Mail
1515
* [Asynchronous Mail Send](asynchronous_mail_send.md)
1616
* [Attachment](attachment.md)
17-
* [Transactional Templates](transational_templates.md)
17+
* [Dynamic Transactional Templates](dynamic_transational_templates.md)
18+
* [Legacy Transactional Templates](legacy_transational_templates.md)
1819

1920
### Library Features
2021
* [Error Handling](error_handling.md)
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Transactional Templates
2+
3+
For this example, we assume you have created a [dynamic transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/how_to_send_an_email_with_transactional_templates.html). Following is the template content we used for testing.
4+
5+
Template ID (replace with your own):
6+
7+
```text
8+
d-5b08559ac97289da39defbb521bc62da
9+
```
10+
11+
Email Subject:
12+
13+
```text
14+
{{subject}}
15+
```
16+
17+
Template Body:
18+
19+
```html
20+
<html>
21+
<head>
22+
<title></title>
23+
</head>
24+
<body>
25+
Hello {{name}},
26+
<br /><br/>
27+
I'm glad you are trying out the template feature!
28+
{{#if city}}
29+
<br /><br/>
30+
I hope you are having a great day in {{city.name}}, {{city.country}} :)
31+
{{/if}}
32+
<br /><br/>
33+
</body>
34+
</html>
35+
```
36+
37+
## With Mail Helper Class
38+
39+
```python
40+
import sendgrid
41+
import os
42+
from sendgrid.helpers.mail import Email, DynamicData, Mail, Personalization
43+
try:
44+
# Python 3
45+
import urllib.request as urllib
46+
except ImportError:
47+
# Python 2
48+
import urllib2 as urllib
49+
50+
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
51+
from_email = Email("test@example.com")
52+
to_email = Email("test@example.com")
53+
mail = Mail(from_email, to_email)
54+
personalization = Personalization()
55+
personalization.add_dynamic_template_data(DynamicData("subject", "Dynamic Templating"))
56+
personalization.add_dynamic_template_data(DynamicData("name", "Example User"))
57+
personalization.add_dynamic_template_data(DynamicData("city", { "name": "Denver", "country": "USA" }))
58+
mail.template_id = "d-5b08559ac97289da39defbb521bc62da"
59+
60+
try:
61+
response = sg.client.mail.send.post(request_body=mail.get())
62+
except urllib.HTTPError as e:
63+
print (e.read())
64+
exit()
65+
print(response.status_code)
66+
print(response.body)
67+
print(response.headers)
68+
```
69+
70+
## Without Mail Helper Class
71+
72+
```python
73+
import sendgrid
74+
import os
75+
try:
76+
# Python 3
77+
import urllib.request as urllib
78+
except ImportError:
79+
# Python 2
80+
import urllib2 as urllib
81+
82+
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
83+
data = {
84+
"personalizations": [
85+
{
86+
"to": [
87+
{
88+
"email": "test@example.com"
89+
}
90+
],
91+
"dynamic_template_data": {
92+
"subject": "Dynamic Templating",
93+
"name": "Example User",
94+
"city": {
95+
"name": "Denver",
96+
"country": "USA"
97+
}
98+
},
99+
},
100+
],
101+
"from": {
102+
"email": "test@example.com"
103+
},
104+
"template_id": "d-5b08559ac97289da39defbb521bc62da"
105+
}
106+
try:
107+
response = sg.client.mail.send.post(request_body=data)
108+
except urllib.HTTPError as e:
109+
print (e.read())
110+
exit()
111+
print(response.status_code)
112+
print(response.body)
113+
print(response.headers)
114+
```

use_cases/transational_templates.md renamed to use_cases/legacy_transational_templates.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Transactional Templates
22

3-
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.
3+
For this example, we assume you have created a [legacy transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). Following is the template content we used for testing.
44

55
Template ID (replace with your own):
66

0 commit comments

Comments
 (0)