Skip to content

Instantly share code, notes, and snippets.

@ramuta
Created March 15, 2017 21:55
Show Gist options
  • Save ramuta/40cb88553620c0a8f35096cb9359a26b to your computer and use it in GitHub Desktop.
Save ramuta/40cb88553620c0a8f35096cb9359a26b to your computer and use it in GitHub Desktop.
How to use sendgrid library
template = "some-template.html"
template_params = {"var1": "value1", "var2": "value2"}
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),
extensions=['jinja2.ext.autoescape'],
autoescape=False)
html_template = jinja_env.get_template(template)
if not template_params:
template_params = {}
html_message_body = html_template.render(template_params)
send_via_sendgrid(sender_email="example@email.si", sender_name="Sender Name", receiver_email="example2@email.si",
email_subject="Some subject", content=html_message_body)
def send_via_sendgrid(sender_email, sender_name, receiver_email, email_subject, content):
SENDGRID_API_KEY = "sendgrid API key"
sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY)
email_message = mail.Mail()
email_message.set_from(mail.Email(sender_email, sender_name))
email_message.set_subject(email_subject)
email_message.add_content(mail.Content("text/html", content))
personalization = mail.Personalization()
personalization.add_to(mail.Email(receiver_email))
email_message.add_personalization(personalization)
try:
response = sg.client.mail.send.post(request_body=email_message.get())
if response.status_code != 200 and response.status_code != 202:
logging.error("status code: " + str(response.status_code))
logging.error("headers: " + str(response.headers))
return logging.error("body: " + str(response.body))
except Exception as e:
logging.error("Error with sending via sendgrid.")
return logging.error(e.message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment