How to use the sendgrid.helpers.mail 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 tytso / xfstests-bld / kvm-xfstests / test-appliance / files / usr / local / lib / gce-ltm / testrunmanager.py View on Github external
or self.report_receiver)
    source_email = sendgrid.helpers.mail.Email(report_sender)
    dest_email = sendgrid.helpers.mail.Email(self.report_receiver)
    logging.debug('email_subject %s, report_sender %s, report_receiver %s',
                  email_subject, report_sender, self.report_receiver)
    try:
      logging.info('Reading reports file as e-mail contents')
      with open(os.path.join(self.agg_results_dir, 'report'), 'r') as ff:
        report_content = sendgrid.helpers.mail.Content('text/plain', ff.read())
    except IOError:
      logging.warning('Unable to read report file for report contents')
      report_content = sendgrid.helpers.mail.Content(
          'text/plain',
          'Could not read contents of report file')
    sg = sendgrid.SendGridAPIClient(apikey=sendgrid_api_key)
    full_email = sendgrid.helpers.mail.Mail(source_email, email_subject,
                                            dest_email, report_content)

    try:
      response = sg.client.mail.send.post(request_body=full_email.get())
    except HTTPError as err:
      # Probably a bad API key. Possible other causes could include sendgrid's
      # API being unavailable, or any other errors that come from the
      # api.sendgrid.com/mail/send endpoint.
      # Docs:
      # https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
      # https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html
      # Common probable occurrences:
      # 401 unauthorized, 403 forbidden, 413 payload too large, 429 too many
      # requests, 500 server unavailable, 503 v3 api unavailable.
      # also, 200 OK and 202 ACCEPTED
      response = err
github forseti-security / forseti-security / google / cloud / security / common / util / email_util.py View on Github external
    @staticmethod
    def _add_recipients(email, email_recipients):
        """Add multiple recipients to the sendgrid email object.

        Args:
            email (SendGrid): SendGrid mail object
            email_recipients (Str): comma-separated text of the email recipients

        Returns:
            SendGrid: SendGrid mail object with mulitiple recipients.
        """
        personalization = mail.Personalization()
        recipients = email_recipients.split(',')
        for recipient in recipients:
            personalization.add_to(mail.Email(recipient))
        email.add_personalization(personalization)
        return email
github forseti-security / forseti-security / google / cloud / security / common / util / email_util.py View on Github external
    @staticmethod
    def _add_recipients(email, email_recipients):
        """Add multiple recipients to the sendgrid email object.

        Args:
            email (SendGrid): SendGrid mail object
            email_recipients (Str): comma-separated text of the email recipients

        Returns:
            SendGrid: SendGrid mail object with mulitiple recipients.
        """
        personalization = mail.Personalization()
        recipients = email_recipients.split(',')
        for recipient in recipients:
            personalization.add_to(mail.Email(recipient))
        email.add_personalization(personalization)
        return email
github Polsaker / throat / app / misc.py View on Github external
def send_email_with_sendgrid(sender, to, subject, html_content):
    """ Send a mail through sendgrid """
    sg = sendgrid.SendGridAPIClient(api_key=config.sendgrid.api_key)

    mail = sendgrid.helpers.mail.Mail(
        from_email=sender,
        to_emails=to,
        subject=subject,
        html_content=html_content)

    sg.send(mail)
github Yelp / love / logic / email.py View on Github external
def send_sendgrid_email(sender, recipient, subject, body_html, body_text):
    key = logic.secret.get_secret('SENDGRID_API_KEY')
    sg = sendgrid.SendGridAPIClient(apikey=key)

    from_ = sendgrid.helpers.mail.Email(*get_name_and_email(sender))
    to = sendgrid.helpers.mail.Email(*get_name_and_email(recipient))
    content_html = sendgrid.helpers.mail.Content('text/html', body_html)
    content_text = sendgrid.helpers.mail.Content('text/plain', body_text)
    # text/plain needs to be before text/html or sendgrid gets mad
    message = sendgrid.helpers.mail.Mail(from_, subject, to, content_text)
    message.add_content(content_html)

    sg.client.mail.send.post(request_body=message.get())
github HaliteChallenge / Halite-III / apiserver / apiserver / notify.py View on Github external
:param str group_id: The group ID of the email.
    pass to the email template.
    """
    mail = sendgrid.helpers.mail.Mail()

    if not recipient.organization:
        recipient = recipient._replace(organization="(no affiliation)")

    mail.from_email = sendgrid.Email("halite@halite.io", "Halite Challenge")
    personalization = sendgrid.helpers.mail.Personalization()
    personalization.add_to(sendgrid.helpers.mail.Email(recipient.email, recipient.username))

    all_substitutions = itertools.chain(
        recipient._asdict().items(), substitutions.items())
    for substitution_key, substitution_value in all_substitutions:
        personalization.add_substitution(sendgrid.helpers.mail.Substitution(
            "-{}-".format(substitution_key), substitution_value))

    mail.add_personalization(personalization)
    mail.template_id = template_id
    mail.asm = sendgrid.helpers.mail.ASM(group_id, [config.GOODNEWS_ACCOMPLISHMENTS, config.GAME_ERROR_MESSAGES, config.RESEARCH_EMAILS, config.NEWSLETTERS_ARTICLES])
    mail.add_category(sendgrid.helpers.mail.Category(category))
    settings = sendgrid.helpers.mail.MailSettings()
    settings.sandbox_mode = sendgrid.helpers.mail.SandBoxMode(config.SENDGRID_SANDBOX_MODE)
    mail.mail_settings = settings

    try:
        response = sg.client.mail.send.post(request_body=mail.get())
    except HTTPError as e:
        app.logger.error("Could not send email", exc_info=e)
        app.logger.error("Response: {}".format(e.body))
github Yelp / love / logic / email.py View on Github external
def send_sendgrid_email(sender, recipient, subject, body_html, body_text):
    key = logic.secret.get_secret('SENDGRID_API_KEY')
    sg = sendgrid.SendGridAPIClient(apikey=key)

    from_ = sendgrid.helpers.mail.Email(*get_name_and_email(sender))
    to = sendgrid.helpers.mail.Email(*get_name_and_email(recipient))
    content_html = sendgrid.helpers.mail.Content('text/html', body_html)
    content_text = sendgrid.helpers.mail.Content('text/plain', body_text)
    # text/plain needs to be before text/html or sendgrid gets mad
    message = sendgrid.helpers.mail.Mail(from_, subject, to, content_text)
    message.add_content(content_html)

    sg.client.mail.send.post(request_body=message.get())
github GoogleCloudPlatform / python-docs-samples / appengine / flexible / sendgrid / main.py View on Github external
def send_email():
    to = request.form.get('to')
    if not to:
        return ('Please provide an email address in the "to" query string '
                'parameter.'), 400

    sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)

    to_email = mail.Email(to)
    from_email = mail.Email(SENDGRID_SENDER)
    subject = 'This is a test email'
    content = mail.Content('text/plain', 'Example message.')
    message = mail.Mail(from_email, subject, to_email, content)

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

    if response.status_code != 202:
        return 'An error occurred: {}'.format(response.body), 500

    return 'Email sent.'
# [END gae_flex_sendgrid]
github forseti-security / forseti-security / google / cloud / security / common / util / email_util.py View on Github external
email_recipient (str): The email recipient.
            email_subject (str): The email subject.
            email_content (str): The email content (aka, body).
            content_type (str): The email content type.
            attachment (Attachment): A SendGrid Attachment.

        Raises:
            EmailSendError: An error with sending email has occurred.
        """
        if not email_sender or not email_recipient:
            LOGGER.warn('Unable to send email: sender=%s, recipient=%s',
                        email_sender, email_recipient)
            raise util_errors.EmailSendError

        email = mail.Mail()
        email.from_email = mail.Email(email_sender)
        email.subject = email_subject
        email.add_content(mail.Content(content_type, email_content))

        email = self._add_recipients(email, email_recipient)

        if attachment:
            email.add_attachment(attachment)

        try:
            response = self._execute_send(email)
        except urllib2.HTTPError as e:
            LOGGER.error('Unable to send email: %s %s',
                         e.code, e.reason)
            raise util_errors.EmailSendError

        if response.status_code == 202:
github GoogleCloudPlatform / python-docs-samples / appengine / standard / sendgrid / main.py View on Github external
def send_simple_message(recipient):
    # [START sendgrid-send]

    sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)

    to_email = mail.Email(recipient)
    from_email = mail.Email(SENDGRID_SENDER)
    subject = 'This is a test email'
    content = mail.Content('text/plain', 'Example message.')
    message = mail.Mail(from_email, subject, to_email, content)

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

    return response
    # [END sendgrid-send]