Skip to content

Commit 68b9eb0

Browse files
Merge branch 'dynamic_template_support' of https://github.com/3lnc/sendgrid-python into 3lnc-dynamic_template_support
2 parents 793aad7 + e1cc256 commit 68b9eb0

File tree

4 files changed

+92
-7
lines changed

4 files changed

+92
-7
lines changed

examples/helpers/mail/mail_example.py renamed to examples/helpers/mail_example.py

Lines changed: 26 additions & 4 deletions
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,27 @@ 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 dynamic_template_usage():
222+
"""
223+
Sample usage of dynamic (handlebars) transactional templates.
224+
To make this work, you should have dynamic template created within your
225+
SendGrid account. For this particular example, template may be like::
226+
227+
<p>Hello, {{name}}! Your current balance is {{balance}}<p>
228+
229+
"""
230+
mail = Mail()
231+
mail.from_email = '[email protected]'
232+
mail.template_id = 'd-your-dynamic-template-uid'
233+
p = Personalization()
234+
p.add_to(Email('[email protected]'))
235+
p.dynamic_template_data = {
236+
'name': 'Bob',
237+
'balance': 42
238+
}
239+
mail.add_personalization(p)
240+
241+
sg = SendGridAPIClient(apikey='SG.your-api-key')
242+
sg.client.mail.send.post(request_body=mail.get())

sendgrid/helpers/mail/personalization.py

Lines changed: 9 additions & 0 deletions
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):
@@ -198,4 +203,8 @@ def get(self):
198203

199204
if self.send_at is not None:
200205
personalization["send_at"] = self.send_at
206+
207+
if self.dynamic_template_data is not None:
208+
personalization['dynamic_template_data'] = self.dynamic_template_data
209+
201210
return personalization

test/test_mail.py

Lines changed: 24 additions & 2 deletions
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

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,38 @@ print(response.body)
6666
print(response.headers)
6767
```
6868

69+
### With dynamic templates
70+
71+
Sendgrid dynamic templates let you leverage power of [handlebars](https://handlebarsjs.com/)
72+
syntax to easily manage complex dynamic content in transactional emails.
73+
74+
To check this example snippet, create
75+
[transactional email template](https://sendgrid.com/dynamic_templates) with code like
76+
```html
77+
<p>Hello, {{name}}! Your current balance is {{balance}}<p>
78+
```
79+
80+
Than send email based on it, providing context for substitutions:
81+
```python
82+
from sendgrid import SendGridAPIClient
83+
from sendgrid.helpers.mail import Email, Personalization
84+
85+
86+
sg = SendGridAPIClient(apikey='SG.your-api-key')
87+
88+
mail = Mail()
89+
mail.from_email='[email protected]'
90+
mail.template_id = 'd-your-dynamic-template-uid'
91+
p = Personalization()
92+
p.add_to(Email('[email protected]'))
93+
p.dynamic_template_data = {'name': 'Bob', 'balance': 42}
94+
mail.add_personalization(p)
95+
96+
sg.client.mail.send.post(request_body=mail.get())
97+
```
98+
99+
Read more about dynamic templates in [docs](https://sendgrid.com/docs/User_Guide/Transactional_Templates/how_to_send_an_email_with_transactional_templates.html)
100+
69101
## Without Mail Helper Class
70102

71103
```python
@@ -113,4 +145,4 @@ except urllib.HTTPError as e:
113145
print(response.status_code)
114146
print(response.body)
115147
print(response.headers)
116-
```
148+
```

0 commit comments

Comments
 (0)