I have integrate the send-grid with my Django application and mails also sent successfully. But now I want to send email with designed template from my django application. I have read the docs also, but not get any idea how to use it programatically. This is my first time to use send-grid. Please can anyone help me to find out the way how can I send send-grid template from django application.
Asked
Active
Viewed 4,742 times
5
-
You might want to try a templating service, like [sendwithus](https://www.sendwithus.com). They support Jinja templates (which are nearly identical to Django), and have a [Python API Client](http://github.com/sendwithus/sendwithus_python). – bvanvugt May 10 '15 at 02:09
-
@bvanvugt the template mean a designed email template which is created in sendgrid account, that I have to fetch and send in email. I dig out the sendgrid docs also but did not get any idea, how to use. – MegaBytes May 10 '15 at 19:56
2 Answers
7
You can use SendGrid's Template Engine to store a template inside SendGrid. You then reference that template ID when sending an email via the SendGrid API, you can see an example of that code in the sendgrid-python library.
Here it is in a full example, it uses a SendGrid API key (you can find out how to get that set up by reading this guide):
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)

Martyn Davies
- 1,493
- 9
- 12
-
Thank you @MartynDavies , I did this, and mail also sent to the recipient id. But the template is not showing instead, in mail I am getting this error. The error detected was: Templates error: 'http_get returned non-20x response: '404 Not Found' body='{"error": "active version not found"}' – MegaBytes May 12 '15 at 08:27
-
1That means that you don't have a template with that specified ID set up inside your SendGrid account, or that the template you made is not yet active. You have to make sure you have an active template in Template Engine, you can see that in the overview here: https://sendgrid.com/docs/User_Guide/Templates/index.html – Martyn Davies May 12 '15 at 08:38
-
Thank you very much, now its done. It was a my mistake that I haven't activate the template. Thanks again – MegaBytes May 12 '15 at 08:56
-
I am facing one issue again, can you suggest me what is going wrong. Now email is delivered to the TO list, but what is happening the substitution values are not displaying in other email ids of TO list. The mail with substitution values are only delivered to the first email id of TO list and for others it is not displaying. I have asked question in sendgrid Community also. The link is: https://community.sendgrid.com/sendgrid/topics/the-email-is-not-sent-to-email-ids-other-than-first-email-id-in-to-list?utm_source=notification&utm_medium=email&utm_campaign=new_reply&utm_content=topic_link – MegaBytes Jun 11 '15 at 10:38
-
@MegaBytes - Let me do some tests and I'll let you know. How many recipients are you putting in the 'to' field? – Martyn Davies Jun 11 '15 at 10:49
-
@MartinDavies max 5 recipient will be in TO list, but even I am sending 2 or 3 it is not gone properly – MegaBytes Jun 12 '15 at 04:52
-
@MegaBytes Are you passing in the multiples as an array? Like this: message.add_to(['Example Dude
', 'john@email.com']) – Martyn Davies Jun 16 '15 at 15:01 -
2
You need Sendgrid-Python interface first:
pip install sendgrid
after that try this:
import os
from sendgrid.helpers.mail import Mail
from sendgrid import SendGridAPIClient
FROM_EMAIL = 'Your_Name@SendGridTest.com'
# update to your dynamic template id from the UI
TEMPLATE_ID = 'd-d027f2806c894df38c59a9dec5460594'
# list of emails and preheader names, update with yours
TO_EMAILS = [('your_email@domain.com', 'Sourabh MbeforL'),]
def SendDynamic():
message = Mail(
from_email=FROM_EMAIL,
to_emails=TO_EMAILS)
# pass custom values for our HTML placeholders
message.dynamic_template_data = {
'subject': 'SendGrid Development',
'place': 'New York City',
'event': 'Twilio Signal'
}
message.template_id = TEMPLATE_ID
try:
sg = SendGridAPIClient(os.environ.get('YOUR_SENDGRID_API_KEY')) ## (^_^) This face is just to grab your attention for api key needed
response = sg.send(message)
code, body, headers = response.status_code, response.body, response.headers
print(f"Response code: {code}")
print(f"Response headers: {headers}")
print(f"Response body: {body}")
print("Dynamic Messages Sent!")
except Exception as e:
print("Error: {0}".format(e))
return str(response.status_code)

nofoobar
- 2,826
- 20
- 24