How to use the sendgrid.helpers.mail.Content 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 sendgrid / sendgrid-python / test / test_mail_helpers.py View on Github external
# Minimum required to send an email
        self.max_diff = None
        mail = Mail()

        mail.from_email = Email("test@example.com")

        mail.subject = "Hello World from the SendGrid Python Library"

        personalization = Personalization()
        personalization.add_to(Email("test@example.com"))
        mail.add_personalization(personalization)

        # Try to include SendGrid API key
        try:
            mail.add_content(
                Content(
                    "text/plain",
                    "some SG.2123b1B.1212lBaC here"))
            mail.add_content(
                Content(
                    "text/html",
                    "some SG.Ba2BlJSDba.232Ln2 here"))

            self.assertEqual(
                json.dumps(
                    mail.get(),
                    sort_keys=True),
                '{"content": [{"type": "text/plain", "value": "some text here"}, '
                '{"type": "text/html", '
                '"value": "some text here"}], '
                '"from": {"email": "test@example.com"}, "personalizations": '
                '[{"to": [{"email": "test@example.com"}]}], '
github tytso / xfstests-bld / kvm-xfstests / test-appliance / files / usr / local / lib / gce-ltm / testrunmanager.py View on Github external
if not sendgrid_api_key:
      logging.warning('No sendgrid api key found. Can\'t send email.')
      return
    logging.debug('Got sendgrid api key')
    email_subject = 'xfstests results %s-%s %s' % (
        LTM.ltm_username, self.id, self.kernel_version)
    report_sender = (gce_funcs.get_email_report_sender()
                     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:
github sendgrid / sendgrid-python / test / test_mail_helpers.py View on Github external
message.from_email = From('dx@example.com', 'DX')

        message.reply_to = ReplyTo('dx_reply@example.com', 'DX Reply')

        message.subject = Subject('Sending with SendGrid is Fun 2')

        message.content = Content(
            MimeType.text,
            'and easy to do anywhere, even with Python')
        message.content = Content(
            MimeType.html,
            '<strong>and easy to do anywhere, even with Python</strong>')
        message.content = [
            Content('text/calendar', 'Party Time!!'),
            Content('text/custom', 'Party Time 2!!')
        ]

        message.attachment = Attachment(
            FileContent('base64 encoded content 1'),
            FileName('balance_001.pdf'),
            FileType('application/pdf'),
            Disposition('attachment'),
            ContentId('Content ID 1'))
        message.attachment = [
            Attachment(
                FileContent('base64 encoded content 2'),
                FileName('banner.png'),
                FileType('image/png'),
                Disposition('inline'),
                ContentId('Content ID 2')),
            Attachment(
github elbuo8 / sendgrid-django / sgbackend / mail.py View on Github external
# Python sendgrid client should improve
        # sendgrid/helpers/mail/mail.py:164
        if not from_name:
            from_name = None
        mail.set_from(Email(from_email, from_name))
        mail.set_subject(email.subject)

        personalization = Personalization()
        for e in email.to:
            personalization.add_to(Email(e))
        for e in email.cc:
            personalization.add_cc(Email(e))
        for e in email.bcc:
            personalization.add_bcc(Email(e))
        personalization.set_subject(email.subject)
        mail.add_content(Content("text/plain", email.body))
        if isinstance(email, EmailMultiAlternatives):
            for alt in email.alternatives:
                if alt[1] == "text/html":
                    mail.add_content(Content(alt[1], alt[0]))
        elif email.content_subtype == "html":
            mail.contents = []
            mail.add_content(Content("text/plain", ' '))
            mail.add_content(Content("text/html", email.body))

        if hasattr(email, 'categories'):
            for c in email.categories:
                mail.add_category(Category(c))

        if hasattr(email, 'custom_args'):
            for k, v in email.custom_args.items():
                mail.add_custom_arg(CustomArg(k, v))
github Gingernaut / microAuth / app / utils / emails.py View on Github external
reset_email = reset_email.replace(
            "{{ttl}}", str(appConfig.PASSWORD_RESET_LINK_TTL_HOURS)
        )
        reset_email = reset_email.replace(
            "{{action_url}}", f"{appConfig.FROM_WEBSITE_URL}/reset/{reset.UUID}"
        )

        name = user.firstName
        if not name:
            name = user.emailAddress
        reset_email = reset_email.replace("{{name}}", name)

        from_email = Email(appConfig.FROM_EMAIL)
        to_email = Email(user.emailAddress)
        subject = f"Password reset requested at {appConfig.FROM_ORG_NAME}"
        content = Content("text/html", reset_email)

        return Mail(from_email, subject, to_email, content)
github sendgrid / sendgrid-python / examples / helpers / mail_example.py View on Github external
CustomArg('transactional4', 'true', p=1)
    ]

    message.send_at = SendAt(1461775052, p=1)

    message.subject = Subject('Sending with SendGrid is Fun 1', p=1)

    # The values below this comment are global to entire message

    message.from_email = From('dx@sendgrid.com', 'DX')

    message.reply_to = ReplyTo('dx_reply@sendgrid.com', 'DX Reply')

    message.subject = Subject('Sending with SendGrid is Fun 2')

    message.content = Content(MimeType.text, 'and easy to do anywhere, even with Python')
    message.content = Content(MimeType.html, '<strong>and easy to do anywhere, even with Python</strong>')
    message.content = [
        Content('text/calendar', 'Party Time!!'),
        Content('text/custom', 'Party Time 2!!')
    ]

    message.attachment = Attachment(FileContent('base64 encoded content 1'),
                                    FileType('application/pdf'),
                                    FileName('balance_001.pdf'),
                                    Disposition('attachment'),
                                    ContentId('Content ID 1'))
    message.attachment = [
        Attachment(FileContent('base64 encoded content 2'),
                FileType('image/png'),
                FileName('banner.png'),
                Disposition('inline'),
github elbuo8 / sendgrid-django / sgbackend / mail.py View on Github external
personalization = Personalization()
        for e in email.to:
            personalization.add_to(Email(e))
        for e in email.cc:
            personalization.add_cc(Email(e))
        for e in email.bcc:
            personalization.add_bcc(Email(e))
        personalization.set_subject(email.subject)
        mail.add_content(Content("text/plain", email.body))
        if isinstance(email, EmailMultiAlternatives):
            for alt in email.alternatives:
                if alt[1] == "text/html":
                    mail.add_content(Content(alt[1], alt[0]))
        elif email.content_subtype == "html":
            mail.contents = []
            mail.add_content(Content("text/plain", ' '))
            mail.add_content(Content("text/html", email.body))

        if hasattr(email, 'categories'):
            for c in email.categories:
                mail.add_category(Category(c))

        if hasattr(email, 'custom_args'):
            for k, v in email.custom_args.items():
                mail.add_custom_arg(CustomArg(k, v))

        if hasattr(email, 'template_id'):
            mail.set_template_id(email.template_id)
            if hasattr(email, 'substitutions'):
                for key, value in email.substitutions.items():
                    personalization.add_substitution(Substitution(key, value))
github cloud-custodian / cloud-custodian / tools / c7n_mailer / c7n_mailer / azure_mailer / sendgrid_delivery.py View on Github external
It also strips out any reserved key headers on the message object.
        """

        mail = Mail(
            from_email=Email(message.get('From')),
            subject=message.get('Subject'),

            # Create a To object instead of an Email object
            to_emails=To(message.get('To')),
        )
        try:
            body = message.get_content()
        except AttributeError:
            # Python2
            body = message.get_payload(decode=True).decode('utf-8')
        mail.add_content(Content(
            message.get_content_type(),
            body.strip()
        ))

        # These headers are not allowed on the message object
        # https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.headers
        skip_headers = [
            'x-sg-id', 'x-sg-eid', 'received', 'dkim-signature', 'Content-Type',
            'Content-Transfer-Encoding', 'To', 'From', 'Subject', 'Reply-To', 'CC', 'BCC'
        ]

        for k, v in message.items():
            if k not in skip_headers:
                mail.add_header(Header(k, v))
        return mail
github Yelp / beans / api / yelp_beans / send_email.py View on Github external
- subject :string => the subject line for the email
            - template :string => the template file, corresponding to the email sent.
            - template_arguments :dictionary => keyword arguments to specify to render_template
        Returns:
            - SendGrid response
    """
    load_secrets()
    env = Environment(loader=PackageLoader('yelp_beans', 'templates'))
    template = env.get_template(template)
    rendered_template = template.render(template_arguments)

    message = mail.Mail(
        from_email=mail.Email(SENDGRID_SENDER),
        subject=subject,
        to_email=mail.Email(email),
        content=Content("text/html", rendered_template)
    )

    return send_grid_client.client.mail.send.post(request_body=message.get())