How do I use a designed template in django using the sendgrid API?

I am integrating a dispatch grid with my Django app and emails are sent successfully as well. But now I want to send an email with a designed template from my django app. I also read the docs but don't understand how to use it programmatically. This is the first time I use send-grid. Please help me find out how can I send the send-grid grid template from django app.

+3


source to share


1 answer


You can use the SendGrid templating engine to store the template inside SendGrid. Then you specify this template ID when sending email via the SendGrid API, see an example of this code in the sendgrid-python library .

Here's a complete example, it uses the SendGrid API key (you can learn how to customize by reading this tutorial ):



import sendgrid

sg = sendgrid.SendGridClient('sendgrid_apikey')

message = sendgrid.Mail()
message.add_to('John Doe <john@email.com>')
message.set_subject('Example')
message.set_html('Body')
message.set_text('Body')
message.set_from('Doe John <doe@email.com>')

# This next section is all to do with Template Engine

# You pass substitutions to your template like this
message.add_substitution('-thing_to_sub-', 'Hello! I am in a template!')

# Turn on the template option
message.add_filter('templates', 'enable', '1')

# Tell SendGrid which template to use
message.add_filter('templates', 'template_id', 'TEMPLATE-ALPHA-NUMERIC-ID')

# Get back a response and status
status, msg = sg.send(message)

      

+5


source







All Articles