Skip to content

Commit 4be8d58

Browse files
Merge branch '3lnc-dynamic_template_support'
2 parents 793aad7 + 28bd2a5 commit 4be8d58

File tree

6 files changed

+148
-9
lines changed

6 files changed

+148
-9
lines changed

docker-test/entrypoint.sh

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,5 @@ fi
1313

1414
cd sendgrid-python
1515
python3.6 setup.py install
16-
pip install pyyaml six werkzeug flask python-http-client
16+
pip install pyyaml six werkzeug flask python-http-client pytest
1717
exec $SHELL

examples/helpers/mail/mail_example.py examples/helpers/mail_example.py

+32-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
import json
2-
import os
3-
import urllib2
1+
from sendgrid import SendGridAPIClient
42
from sendgrid.helpers.mail import *
5-
from sendgrid import *
3+
64

75
# NOTE: you will need move this file to the root
86
# directory of this project to execute properly.
@@ -218,3 +216,33 @@ def send_kitchen_sink():
218216

219217
# this will only send an email if you set SandBox Mode to False
220218
send_kitchen_sink()
219+
220+
221+
def transactional_template_usage():
222+
# Assumes you set your environment variable:
223+
# https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key
224+
225+
"""
226+
Sample usage of dynamic (handlebars) transactional templates.
227+
To make this work, you should have dynamic template created within your
228+
SendGrid account. For this particular example, template may be like::
229+
230+
<p>Hello, {{name}}! Your current balance is {{balance}}<p>
231+
232+
"""
233+
mail = Mail()
234+
mail.from_email = Email('[email protected]')
235+
mail.template_id = 'd-your-dynamic-template-uid'
236+
p = Personalization()
237+
p.add_to(Email('[email protected]'))
238+
p.dynamic_template_data = {
239+
'name': 'Bob',
240+
'balance': 42
241+
}
242+
mail.add_personalization(p)
243+
244+
sg = SendGridAPIClient()
245+
response = sg.client.mail.send.post(request_body=mail.get())
246+
print(response.status_code)
247+
print(response.headers)
248+
print(response.body)

sendgrid/helpers/mail/mail.py

+3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""v3/mail/send response body builder"""
22
from .personalization import Personalization
33
from .header import Header
4+
from .email import Email
45

56

67
class Mail(object):
@@ -147,6 +148,8 @@ def from_email(self):
147148

148149
@from_email.setter
149150
def from_email(self, value):
151+
if isinstance(value, str):
152+
value = Email(value)
150153
self._from_email = value
151154

152155
@property

sendgrid/helpers/mail/personalization.py

+21
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
class Personalization(object):
22
"""A Personalization defines who should receive an individual message and
33
how that message should be handled.
4+
5+
:var dynamic_template_data: data for dynamic transactional template.
6+
Should be JSON-serializeable structure. No pre-processing sill be done
7+
prior to sending this via http client.
48
"""
59

610
def __init__(self):
@@ -13,6 +17,7 @@ def __init__(self):
1317
self._substitutions = []
1418
self._custom_args = []
1519
self._send_at = None
20+
self._dynamic_template_data = None
1621

1722
@property
1823
def tos(self):
@@ -158,6 +163,18 @@ def send_at(self):
158163
def send_at(self, value):
159164
self._send_at = value
160165

166+
@property
167+
def dynamic_template_data(self):
168+
"""Data for dynamic transactional template.
169+
170+
:rtype: JSON-serializeable structure
171+
"""
172+
return self._dynamic_template_data
173+
174+
@dynamic_template_data.setter
175+
def dynamic_template_data(self, json):
176+
self._dynamic_template_data = json
177+
161178
def get(self):
162179
"""
163180
Get a JSON-ready representation of this Personalization.
@@ -198,4 +215,8 @@ def get(self):
198215

199216
if self.send_at is not None:
200217
personalization["send_at"] = self.send_at
218+
219+
if self.dynamic_template_data is not None:
220+
personalization['dynamic_template_data'] = self.dynamic_template_data
221+
201222
return personalization

test/test_mail.py

+24-2
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,6 @@ def test_sendgridAPIKey(self):
8080
else:
8181
self.fail("Should have failed as SendGrid API key included")
8282

83-
8483
def test_helloEmail(self):
8584
self.max_diff = None
8685

@@ -130,7 +129,7 @@ def test_helloEmailAdditionalContent(self):
130129
personalization = Personalization()
131130
personalization.add_to(Email("[email protected]"))
132131
mail.add_personalization(personalization)
133-
132+
134133
mail.add_content(Content("text/html", "<html><body>some text here</body></html>"))
135134
mail.add_content(Content("text/plain", "some text here"))
136135

@@ -562,3 +561,26 @@ def test_disable_tracking(self):
562561
def test_directly_setting_substitutions(self):
563562
personalization = Personalization()
564563
personalization.substitutions = [{'a': 0}]
564+
565+
def test_dynamic_template_data(self):
566+
p = Personalization()
567+
p.add_to(Email('[email protected]'))
568+
p.dynamic_template_data = {
569+
'customer': {
570+
'name': 'Bob',
571+
'returning': True
572+
},
573+
'total': 42
574+
}
575+
576+
expected = {
577+
'to': [{'email': '[email protected]'}],
578+
'dynamic_template_data': {
579+
'customer': {
580+
'name': 'Bob',
581+
'returning': True
582+
},
583+
'total': 42
584+
}
585+
}
586+
self.assertDictEqual(p.get(), expected)

use_cases/transational_templates.md

+67-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,71 @@
1-
# Transactional Templates
1+
### 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+
Sendgrid transactional templates let you leverage power of [handlebars](https://handlebarsjs.com/)
4+
syntax to easily manage complex dynamic content in transactional emails.
5+
6+
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.
7+
8+
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.
9+
10+
Template ID (replace with your own):
11+
12+
```text
13+
d-13b8f94fbcae4ec6b75270d6cb59f932
14+
```
15+
16+
Email Subject:
17+
18+
```text
19+
{{ subject }}
20+
```
21+
22+
Template Body:
23+
24+
```html
25+
<html>
26+
<head>
27+
<title></title>
28+
</head>
29+
<body>
30+
Hello {{ name }},
31+
<br /><br/>
32+
I'm glad you are trying out the template feature!
33+
<br /><br/>
34+
I hope you are having a great day in {{ city }} :)
35+
<br /><br/>
36+
</body>
37+
</html>
38+
```
39+
40+
```python
41+
from sendgrid import SendGridAPIClient
42+
from sendgrid.helpers.mail import Mail, Email, Personalization
43+
44+
45+
sg = SendGridAPIClient()
46+
mail = Mail()
47+
mail.from_email = Email('[email protected]')
48+
mail.template_id = 'd-your-dynamic-template-uid'
49+
p = Personalization()
50+
p.add_to(Email('[email protected]'))
51+
p.dynamic_template_data = {
52+
'subject': 'Dynamic Templates in Python',
53+
'name': 'Example User',
54+
'city': 'Denver'
55+
}
56+
mail.add_personalization(p)
57+
58+
response = sg.client.mail.send.post(request_body=mail.get())
59+
print(response.status_code)
60+
print(response.headers)
61+
print(response.body)
62+
```
63+
64+
Read more about dynamic templates [here](https://sendgrid.com/docs/User_Guide/Transactional_Templates/how_to_send_an_email_with_transactional_templates.html).
65+
66+
# Legacy Templates
67+
68+
For this example, we assume you have created a [Legacy Template](https://sendgrid.com/templates). Following is the template content we used for testing.
469

570
Template ID (replace with your own):
671

0 commit comments

Comments
 (0)