Rajat Gupta
Rajat Gupta

Reputation: 1959

How to integrate sendgrid templates with python app?`

I want to integrate the template which I made on the Sendgrid Template Engine with my python application. I read the documentation and the source code on GitHub, but It give me error like this:

HTTP 400; JSON in headers is valid but incompatible

My source code is:

import sendgrid
import json
import os


mail_to = raw_input("Reciever's Mail(Name <email>): ")
subject = raw_input('Subject: ')
mail_from = raw_input("Sender Mail(Name <email>): ")


API_USER = os.getenv('API_USER')
API_KEY = os.getenv('API_KEY')

sg = sendgrid.SendGridClient(API_USER, API_KEY)

plaintext = \
    """
        <strong>This mail is only for testing.</strong>
    """
htmlbody = \
    """
      Html Data
    """

header_json = {
    'filters': {
        'templates': {
            'setting': {
                'enabled': '1',
                'template_id': '6967292-382-43aa-89dd-41fcd09b3fec'
            }
        }
    }
}

message = sendgrid.Mail(headers={'X-SMTPAPI': header_json})
message.add_to(mail_to)
message.set_subject(subject)
message.set_html(htmlbody)
message.set_text(plaintext)
message.set_from(mail_from)

status, msg = sg.send(message)

print "HTTP STATUS", status

msg = json.loads(msg)

if status == 400:
    print msg

Can someone tell me how to integrate my template with my app?

Upvotes: 4

Views: 2505

Answers (1)

eddiezane
eddiezane

Reputation: 916

Template support is built into the SendGrid-Python library. From the README:

message = sendgrid.Mail()
message.add_filter('templates', 'enable', '1')
message.add_filter('templates', 'template_id', 'TEMPLATE-ALPHA-NUMERIC-ID')

It's also best to let the smtpapi-python library build the SMTPAPI header for you. This is actually transmitted as a POST parameter - not HTTP header. The name comes from before SendGrid's Web API existed and it was actually sent as an SMTP header.

Upvotes: 4

Related Questions