Created
March 15, 2017 21:55
-
-
Save ramuta/40cb88553620c0a8f35096cb9359a26b to your computer and use it in GitHub Desktop.
How to use sendgrid library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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="[email protected]", sender_name="Sender Name", receiver_email="[email protected]", | |
email_subject="Some subject", content=html_message_body) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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