How to use the sendgrid.helpers.mail.Email 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_email.py View on Github external
def test_add_rfc_email(self):
        name = "SomeName"
        address = "test@example.com"
        name_address = "{} <{}>".format(name, address)
        email = Email(name_address)
        self.assertEqual(email.name, name)
        self.assertEqual(email.email, "test@example.com")
github cloud-custodian / cloud-custodian / tools / c7n_mailer / c7n_mailer / azure_mailer / sendgrid_delivery.py View on Github external
def _sendgrid_mail_from_email_message(message):
        """
        Create a Mail object from an instance of email.message.EmailMessage.

        This is a copy and tweak of Mail.from_EmailMessage from the SendGrid SDK
        to get around a bug where it creates an Email object and later requires
        that object to be an instance of a To, Cc, or Bcc object.

        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
github Yelp / beans / api / yelp_beans / send_email.py View on Github external
- email :string => the user's work email (ie username@company.com)
            - 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())
github uyamazak / oceanus / revelation / app / tasks / plugins / sendgrid.py View on Github external
def send2email(self, kwargs):
        subject = kwargs.get("subject")
        body = kwargs.get("body")
        sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
        from_email = Email(SENDGRID_FROM_EMAIL)
        to_email = Email(SENDGRID_TO_EMAIL)
        content = Content("text/html", body)
        mail = Mail(from_email, subject, to_email, content)
        response = sg.client.mail.send.post(request_body=mail.get())
        return response.status_code
github UCCNetsoc / netsocadmin2 / netsocadmin / mail_helper.py View on Github external
def send_mail(from_mail: str, to_mail: str, subject: str, content: str, cc: List[str] = None) -> object:
    sg = sendgrid.SendGridAPIClient(config.SENDGRID_KEY)

    mail = Mail()
    mail.from_email = From(from_mail, "UCC Netsoc")
    mail.subject = subject
    mail.content = Content("text/plain", content)

    p = sendgrid.Personalization()
    p.add_to(To(to_mail))
    if cc:
        for email in cc:
            p.add_cc(Email(email))
    mail.add_personalization(p)
    return sg.send(mail)
github brenokcc / djangoplus / mail / __init__.py View on Github external
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 sklarsa / django-sendgrid-v5 / sendgrid_backend / mail.py View on Github external
personalization.send_at = msg.send_at

        mail.add_personalization(personalization)

        if hasattr(msg, "reply_to") and msg.reply_to:
            if mail.reply_to:
                # If this code path is triggered, the reply_to on the sg mail was set in a header above
                reply_to = Email(*self._parse_email_address(msg.reply_to))
                if reply_to.email != mail.reply_to.email or reply_to.name != mail.reply_to.name:
                    raise ValueError("Sendgrid only allows 1 email in the reply-to field.  " +
                                     "Reply-To header value != reply_to property value.")

            if not isinstance(msg.reply_to, basestring):
                if len(msg.reply_to) > 1:
                    raise ValueError("Sendgrid only allows 1 email in the reply-to field")
                mail.reply_to = Email(*self._parse_email_address(msg.reply_to[0]))
            else:
                mail.reply_to = Email(*self._parse_email_address(msg.reply_to))

        for attch in msg.attachments:
            sg_attch = self._create_sg_attachment(attch)
            mail.add_attachment(sg_attch)

        msg.body = ' ' if msg.body == '' else msg.body

        if isinstance(msg, EmailMultiAlternatives):
            mail.add_content(Content("text/plain", msg.body))
            for alt in msg.alternatives:
                if alt[1] == "text/html":
                    mail.add_content(Content(alt[1], alt[0]))
        elif msg.content_subtype == "html":
            mail.add_content(Content("text/plain", " "))
github elbuo8 / sendgrid-django / sgbackend / mail.py View on Github external
def _build_sg_mail(self, email):
        mail = Mail()
        from_name, from_email = rfc822.parseaddr(email.from_email)
        # 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))
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 elbuo8 / sendgrid-django / sgbackend / mail.py View on Github external
def _build_sg_mail(self, email):
        mail = Mail()
        from_name, from_email = rfc822.parseaddr(email.from_email)
        # 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'):