Skip to content

Instantly share code, notes, and snippets.

@ItIsJustChad
Last active August 10, 2020 12:15
Show Gist options
  • Save ItIsJustChad/864c32a6b8e5f7f91a71e1aed6e2065d to your computer and use it in GitHub Desktop.
Save ItIsJustChad/864c32a6b8e5f7f91a71e1aed6e2065d to your computer and use it in GitHub Desktop.
Using Email Template with SendGrid and Python
#!/usr/bin/python3
from sendgrid.helpers.mail import *
from sendgrid import *
import urllib
def create_content():
#you can creatively come up with dynamic content
person = "Chad"
line = "<table><tr><th>Col 1</th><th>Col 2</th></tr><tr><td>{0}</td><td>Row 1 Col 2</td></td></table>".format(person)
return line
def personalize(html):
emails = ["[email protected]","[email protected]"]
personalization = Personalization()
#make sure your template has a Substitution tag somewhere in it like "-Table-"
personalization.add_substitution(Substitution("-Table-",html))
for email in emails:
personalization.add_to(Email(email))
return personalization
def main():
#generate HTML
html = create_content()
if html is not False:
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
mail = Mail()
mail.from_email = Email("[email protected]","Not Chad")
mail.template_id = "enter-your-template-id-here-from-sendgrid"
mail.add_personalization(personalize(html))
try:
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status)
except urllib.error.HTTPError as e:
print(e.read())
@androane
Copy link

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment