Skip to content

Adds support for dynamic template data in personalizations #593

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -217,3 +215,27 @@ 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::

<p>Hello, {{name}}! Your current balance is {{balance}}<p>

"""
mail = Mail()
mail.from_email = '[email protected]'
mail.template_id = 'd-your-dynamic-template-uid'
p = Personalization()
p.add_to(Email('[email protected]'))
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())
9 changes: 9 additions & 0 deletions sendgrid/helpers/mail/personalization.py
Original file line number Diff line number Diff line change
@@ -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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo: sillwill

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Fixed :)

prior to sending this via http client.
"""

def __init__(self):
Expand All @@ -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):
Expand Down Expand Up @@ -198,4 +203,8 @@ def get(self):

if self.send_at is not None:
personalization["send_at"] = self.send_at

if self.dynamic_template_data is not None:
personalization['dynamic_template_data'] = self.dynamic_template_data

return personalization
26 changes: 24 additions & 2 deletions test/test_mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ def test_sendgridAPIKey(self):
else:
self.fail("Should have failed as SendGrid API key included")


def test_helloEmail(self):
self.max_diff = None

Expand Down Expand Up @@ -130,7 +129,7 @@ def test_helloEmailAdditionalContent(self):
personalization = Personalization()
personalization.add_to(Email("[email protected]"))
mail.add_personalization(personalization)

mail.add_content(Content("text/html", "<html><body>some text here</body></html>"))
mail.add_content(Content("text/plain", "some text here"))

Expand Down Expand Up @@ -562,3 +561,26 @@ 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('[email protected]'))
p.dynamic_template_data = {
'customer': {
'name': 'Bob',
'returning': True
},
'total': 42
}

expected = {
'to': [{'email': '[email protected]'}],
'dynamic_template_data': {
'customer': {
'name': 'Bob',
'returning': True
},
'total': 42
}
}
self.assertDictEqual(p.get(), expected)
34 changes: 33 additions & 1 deletion use_cases/transational_templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,38 @@ print(response.body)
print(response.headers)
```

### With dynamic templates
Copy link
Contributor

@af4ro af4ro Aug 9, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be missing dynamic template updates in the rest of the templates file like here and here

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can check out some of the changes made here in #597

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding updates for rest of file: this is left on purpose, as old template system is still in place, as well as code to support it. So, I guess we still need documentation for it.

Or I'm missing the point


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
<p>Hello, {{name}}! Your current balance is {{balance}}<p>
```

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='[email protected]'
mail.template_id = 'd-your-dynamic-template-uid'
p = Personalization()
p.add_to(Email('[email protected]'))
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
Expand Down Expand Up @@ -113,4 +145,4 @@ except urllib.HTTPError as e:
print(response.status_code)
print(response.body)
print(response.headers)
```
```