How to use the sendgrid.SendGridAPIClient function in sendgrid

To help you get started, we’ve selected a few sendgrid examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lingthio / Flask-User / flask_user / email_adapters / sendgrid_email_adapter.py View on Github external
Args:
            app(Flask): The Flask application instance.
        """

        super(SendgridEmailAdapter, self).__init__(app)

        sendgrid_api_key = app.config.get('SENDGRID_API_KEY')
        if not sendgrid_api_key:
            raise ConfigError(
                "The SENDGRID_API_KEY setting is missing. Set SENDGRID_API_KEY in your app config.")

        # Setup sendgrid-python
        try:
            from sendgrid import SendGridAPIClient
            self.sg = SendGridAPIClient(apikey=sendgrid_api_key)
        except ImportError:
            raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)
github okpy / ok / server / utils.py View on Github external
def _get_sendgrid_api_client():
    if constants.SENDGRID_KEY:
        return sendgrid.SendGridAPIClient(apikey=constants.SENDGRID_KEY)

    raise ValueError('no sendgrid credentials available')
github garoa / sistema-tesouraria / geral / form.py View on Github external
def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        #email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
        #if html_email_template_name is not None:
        #    html_email = loader.render_to_string(html_email_template_name, context)
        #    email_message.attach_alternative(html_email, 'text/html')

        sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
        subject = loader.render_to_string(subject_template_name, context)
        from_email = Email("tesZureirZ@garZa.net.br".replace('Z', 'o'))
        to_email = Email(to_email)
        body = Content("text/plain",
                loader.render_to_string(email_template_name, context))
        mail = Mail(from_email, subject, to_email, body)

        response = sg.client.mail.send.post(request_body=mail.get())

        print(response.status_code)
        print(response.body)
        print(response.headers)
github sendgrid / sendgrid-python / examples / templates / templates.py View on Github external
import sendgrid
import json
import os


sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))

##################################################
# Create a transactional template. #
# POST /templates #

data = {
    "name": "example_name"
}
response = sg.client.templates.post(request_body=data)
print(response.status_code)
print(response.body)
print(response.headers)

##################################################
# Retrieve all transactional templates. #
# GET /templates #
github sendgrid / sendgrid-python / examples / browsers / browsers.py View on Github external
import sendgrid
import json
import os


sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))

##################################################
# Retrieve email statistics by browser.  #
# GET /browsers/stats #

params = {'end_date': '2016-04-01',
          'aggregated_by': 'day',
          'browsers': 'test_string',
          'limit': 'test_string',
          'offset': 'test_string',
          'start_date': '2016-01-01'}
response = sg.client.browsers.stats.get(query_params=params)
print(response.status_code)
print(response.body)
print(response.headers)
github brenokcc / djangoplus / mail / __init__.py View on Github external
context['project_url'] = url
    context['project_name'] = app_settings.initials
    context['project_description'] = app_settings.name
    context['project_logo'] = app_settings.logo and \
        '{}/media/{}'.format(url, app_settings.logo) or '{}/static/images/mail.png'.format(url)
    context['actions'] = actions
    context['message'] = message.replace('\n', '<br>').replace('\t', '&nbsp;'*4)
    reply_to = reply_to and [reply_to] or None
    from_email = 'Não-Responder &lt;{}&gt;'.format(settings.SERVER_EMAIL)
    html = loader.render_to_string('mail.html', context)

    if settings.SENDGRID_KEY and 'test' not in sys.argv:
        import sendgrid
        from sendgrid.helpers.mail import Email, Content, Mail

        sg_client = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_KEY)
        from_email = Email(settings.SERVER_EMAIL)
        to_email = Email(send_to)
        content = Content("text/html", html)
        mail = Mail(from_email, subject, to_email, content)
        if reply_to:
            mail.reply_to = Email(reply_to)
        response = sg_client.client.mail.send.post(request_body=mail.get())
        return response.status_code
    else:
        body = 'Mensagem em anexo.'
        email = EmailMultiAlternatives(subject, body, from_email, [send_to], reply_to=reply_to)
        email.attach_alternative(html, "text/html")
        return email.send()
github PruthviKumarBK / PROTON / nucleus / email / email.py View on Github external
from configuration import ProtonConfig
from nucleus.generics.log_utilities import LogUtilities

__author__ = "Pruthvi Kumar, pruthvikumar.123@gmail.com"
__copyright__ = "Copyright (C) 2018 Pruthvi Kumar | http://www.apricity.co.in"
__license__ = "BSD 3-Clause License"
__version__ = "1.0"


class ProtonEmail(object):
    """
    PROTONs email client.
    """
    email_logger = LogUtilities().get_logger(log_file_name='emailer_logs',
                                             log_file_path='{}/trace/emailer_logs.log'.format(ProtonConfig.ROOT_DIR))
    __sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))

    def __init__(self):
        super(ProtonEmail, self).__init__()

    @staticmethod
    def __email_decorator(html_content):
        """
        Decorates email with disclaimer, logo and other good formatting.
        :param html_content: The content that user desires
        :return: Formatted HTML content.
        """
        dont_reply_warning_text = '<strong>PS: Please do not reply to this email. This email may not be monitored. ' \
                                  'For any queries, please contact support ' \
                                  'for {} at {}.</strong>'.format(os.environ.get('APP_NAME'),
                                                                  os.environ.get('APP_SUPPORT_EMAIL'))
github FroggyTaipei / froggy-service / backend / apps / mails / models.py View on Github external
from sendgrid.helpers.mail import Email, Mail
from django.contrib.postgres.fields import HStoreField
from django.db.models import (
    Model,
    CASCADE,
    DateTimeField,
    ForeignKey,
    EmailField,
    BooleanField,
    CharField,
)

from .utils import sendgrid_system_mail

env = environ.Env()
sg = sendgrid.SendGridAPIClient(apikey=env.str('SENDGRID_API_KEY', default=''))


class SendGridMailTemplate(Model):
    """SendGrid樣板"""
    tid = CharField(max_length=255, verbose_name=_('Template Id'))
    name = CharField(max_length=50, verbose_name=_('Name'))
    update_time = DateTimeField(auto_now=True, null=True, blank=True, verbose_name=_('Updated Time'))

    class Meta:
        verbose_name = _('SendGrid Template')
        verbose_name_plural = _('SendGrid Template')
        ordering = ('name',)

    def __str__(self):
        return self.name
github HaliteChallenge / Halite-III / apiserver / apiserver / notify.py View on Github external
import collections
import itertools
import json
import sendgrid
import sendgrid.helpers
import sendgrid.helpers.mail

from python_http_client.exceptions import HTTPError

from . import app, config


sg = sendgrid.SendGridAPIClient(apikey=config.SENDGRID_API_KEY)


Recipient = collections.namedtuple("Recipient", [
    "user_id",
    "username",
    "email",
    "organization",
    "level",
    "date_created",
])


def send_notification(recipient_email, recipient_name, subject, body,
                      attachments=None):
    mail = sendgrid.helpers.mail.Mail()
github sendgrid / sendgrid-python / examples / devices / devices.py View on Github external
import sendgrid
import json
import os


sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))

##################################################
# Retrieve email statistics by device type. #
# GET /devices/stats #

params = {'aggregated_by': 'day', 'limit': 1,
          'start_date': '2016-01-01',
          'end_date': '2016-04-01',
          'offset': 1}
response = sg.client.devices.stats.get(query_params=params)
print(response.status_code)
print(response.body)
print(response.headers)