Skip to content

Instantly share code, notes, and snippets.

@alexanderlamb
Created November 29, 2016 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexanderlamb/dd3c376cc715e3e070d08f584e097d76 to your computer and use it in GitHub Desktop.
Save alexanderlamb/dd3c376cc715e3e070d08f584e097d76 to your computer and use it in GitHub Desktop.
import sendgrid
from sendgrid.helpers.mail import *
class FlaskSendGrid(object):
app = None
api_key = None
default_from = None
def __init__(self, app=None, **opts):
if app:
self.init_app(app)
def init_app(self, app):
self.app = app
self.api_key = app.config['SENDGRID_API_KEY']
self.default_from = app.config['SENDGRID_DEFAULT_FROM']
def send_email(self, **opts):
if not opts.get('from_email', None) and not self.default_from:
raise ValueError('No from email or default_from was configured')
sg = sendgrid.SendGridAPIClient(apikey=self.api_key)
message = Mail()
personalization = Personalization()
for _ in opts['to']:
personalization.add_to(Email(_['email']))
substitutions = opts.get('substitutions', dict()).items()
for key, value in substitutions:
personalization.add_substitution(Substitution(key, value))
message.add_personalization(personalization)
if opts.get('template_id', None):
message.set_template_id(opts['template_id'])
from_email = opts.get('from_email', None) or self.default_from
message.set_from(Email(from_email['email'], from_email['name']))
message.set_subject(opts['subject'])
data = message.get()
response = sg.client.mail.send.post(request_body=data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment