How to use the sendgrid.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 bitslabsyr / stack / scripts / notifications / notifier.py View on Github external
def send_email(report, title):
    API_KEY = os.environ.get('SENDGRID_KEY')
    if API_KEY is None:
        print 'No SendGrid API key found! Please set the SENDGRID_KEY env var'
        sys.exit(1)

    sg = SendGridClient(API_KEY, raise_errors=True)

    # Backwards compatability for emails stored as strings, not lists
    emails = report['project_details']['email']
    if type(emails) is not list:
        emails = [emails]

    for address in emails:
        message = Mail()
        message.add_to(address)
        message.set_subject(title)
        message.set_html(generate_email_text(report))
        message.set_from('STACKS ')

        try:
            sg.send(message)
        except SendGridError as e:
            print e
        except SendGridClientError as e:
            print e
        except SendGridServerError as e:
            print e
github shashankredemption / slack-cleaning-bot / slack_cleaning_bot.py View on Github external
def slack_cleaning_bot():
    slack = Slacker(os.environ['SLACK_KEY'])
    people = ['canzhi', 'stevensuckscock', 'neeloy', 'rohan', 'amillman', 'steven']
    day_of_year = datetime.now(tz=timezone('US/Pacific')).timetuple().tm_yday
    message = "today is @" + str(people[day_of_year%6]) + "'s day to do the dishes. Tomorow is @" + str(people[(day_of_year+1)%6])
    slack.chat.post_message('#cleaning', message)
    im_david = '👀 good shit go౦ԁ sHit👌 thats ✔ some good👌shit right👌there👌👌 rightthere ✔if i do ƽaү so my self'.decode('utf-8')
    david_message = sendgrid.Mail(to='david@dtbui.com', subject=im_david, html='<strong>' + message + '</strong>', text=message, from_email="shashank@thenothing.co")
    message = sendgrid.Mail(to='rohanpai@berkeley.edu', subject='CLEAN THE DISHWASHER TODAY', html='<strong> IT IS YOUR LUCKY DAY MOTHAFUCKA</strong>', text='IT IS YOUR LUCKY DAY MOTHAFUCKA', from_email="shashank@thenothing.co")
    try:
        d_status, d_msg = sg.send(david_message)
        if people[day_of_year%6] == 'rohan':
            status, msg = sg.send(message)
    except SendGridClientError:
        print "client messsed up"
    except SendGridServerError:
        print "server messsed up"
github jpf / sms-via-email / app.py View on Github external
@app.route('/handle-sms', methods=['POST'])
def handle_sms():
    lookup = Lookup()
    try:
        email = {
            'text': request.form['Body'],
            'subject': 'Text message',
            'from_email': phone_to_email(request.form['From']),
            'to': lookup.email_for_phone(request.form['To'])
        }
    except InvalidInput, e:
        return warn(str(e)), 400

    message = sendgrid.Mail(**email)
    (status, msg) = sendgrid_api.send(message)
    if 'errors' in msg:
        template = "Error sending message to SendGrid: {}"
        errors = ', '.join(msg['errors'])
        error_message = template.format(errors)
        return warn(error_message), 400
    else:
        return ''
github Khan / alertlib / alertlib / email.py View on Github external
def _send_to_sendgrid(self, message, email_addresses, cc=None, bcc=None,
                          sender=None):
        username = (base.secret('sendgrid_low_priority_username') or
                    base.secret('sendgrid_username'))
        password = (base.secret('sendgrid_low_priority_password') or
                    base.secret('sendgrid_password'))
        assert username and password, "Can't find sendgrid username/password"
        client = sendgrid.SendGridClient(username, password, raise_errors=True)

        # The sendgrid API client auto-utf8-izes to/cc/bcc, but not
        # subject/text.  Shrug.
        msg = sendgrid.Mail(
            subject=self._get_summary().encode('utf-8'),
            to=email_addresses,
            cc=cc,
            bcc=bcc)
        if self.html:
            # TODO(csilvers): convert the html to text for 'body'.
            # (see base.py about using html2text or similar).
            msg.set_text(message.encode('utf-8'))
            msg.set_html(message.encode('utf-8'))
        else:
            msg.set_text(message.encode('utf-8'))
        # Can't be keyword arg because those don't parse "Name "
        # format.
        msg.set_from(_get_sender(sender))

        client.send(msg)
github GoogleCloudPlatform / python-docs-samples / managed_vms / 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.SendGridClient(SENDGRID_API_KEY)

    message = sendgrid.Mail(
        to=to,
        subject='This is a test email',
        html='<p>Example HTML body.</p>',
        text='Example text body.',
        from_email=SENDGRID_SENDER)

    status, response = sg.send(message)

    if status != 200:
        return 'An error occurred: {}'.format(response), 500

    return 'Email sent.'
# [END example]
github craiglabenz / django-grapevine / grapevine / emails / backends / sendgrid_driver.py View on Github external
def as_message(email):
        """
        Takes a ``grapevine.emails.Email`` model and converts it
        into a ``sendgrid.Mail`` object.
        """
        message = sendgrid.Mail()
        message.add_to(email.to)
        message.add_to(email.cc)
        message.add_bcc(email.bcc)
        message.set_text(email.text_body)
        message.set_html(email.html_body)
        message.set_subject(email.subject)
        message.set_from(email.from_email)
        message.set_replyto(email.reply_to)

        # Grapevine GUID
        message.add_unique_arg(EmailBackend.UNIQUE_ARG_NAME, email.guid)

        for variable in email.variables.all():
            if not bool(variable.value):
                message.add_category(variable.key)
            else:
github crowdresearch / daemo / crowdsourcing / backends / sendgrid_backend.py View on Github external
def _create_mail(self, email):
        """A helper method that creates mail for sending."""
        if not email.recipients():
            return False

        from_email = sanitize_address(email.from_email, email.encoding)
        recipients = [sanitize_address(addr, email.encoding)
                      for addr in email.recipients()]

        mail = sendgrid.Mail()
        mail.add_to(recipients)
        mail.add_cc(email.cc)
        mail.add_bcc(email.bcc)
        mail.set_text(email.body)
        mail.set_subject(email.subject)
        mail.set_from(from_email)
        mail.set_replyto(email.reply_to[0] if len(email.reply_to) else '')

        if isinstance(email, EmailMultiAlternatives):
            for alt in email.alternatives:
                if alt[1] == "text/html":
                    mail.set_html(alt[0])

        for attachment in email.attachments:
            if isinstance(attachment, MIMEBase):
                mail.add_attachment_stream(
github shashankredemption / slack-cleaning-bot / slack_cleaning_bot.py View on Github external
def slack_cleaning_bot():
    slack = Slacker(os.environ['SLACK_KEY'])
    people = ['canzhi', 'stevensuckscock', 'neeloy', 'rohan', 'amillman', 'steven']
    day_of_year = datetime.now(tz=timezone('US/Pacific')).timetuple().tm_yday
    message = "today is @" + str(people[day_of_year%6]) + "'s day to do the dishes. Tomorow is @" + str(people[(day_of_year+1)%6])
    slack.chat.post_message('#cleaning', message)
    im_david = '👀 good shit go౦ԁ sHit👌 thats ✔ some good👌shit right👌there👌👌 rightthere ✔if i do ƽaү so my self'.decode('utf-8')
    david_message = sendgrid.Mail(to='david@dtbui.com', subject=im_david, html='<strong>' + message + '</strong>', text=message, from_email="shashank@thenothing.co")
    message = sendgrid.Mail(to='rohanpai@berkeley.edu', subject='CLEAN THE DISHWASHER TODAY', html='<strong> IT IS YOUR LUCKY DAY MOTHAFUCKA</strong>', text='IT IS YOUR LUCKY DAY MOTHAFUCKA', from_email="shashank@thenothing.co")
    try:
        d_status, d_msg = sg.send(david_message)
        if people[day_of_year%6] == 'rohan':
            status, msg = sg.send(message)
    except SendGridClientError:
        print "client messsed up"
    except SendGridServerError:
        print "server messsed up"
github MicroPyramid / django-simple-forum / django_simple_forum / sending_mail.py View on Github external
def Memail(mto, mfrom, msubject, mbody, email_template_name, context):
    if settings.MAIL_SENDER == 'AMAZON':
        sending_mail(msubject, email_template_name, context, mfrom, mto)
    elif settings.MAIL_SENDER == 'MAILGUN':
        requests.post(
            settings.MGUN_API_URL,
            auth=('api', settings.MGUN_API_KEY),
            data={
                'from': mfrom,
                'to': mto,
                'subject': msubject,
                'html': mbody
            })
    elif settings.MAIL_SENDER == 'SENDGRID':
        sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD)
        sending_msg = sendgrid.Mail()
        sending_msg.set_subject(msubject)
        sending_msg.set_html(mbody)
        sending_msg.set_text(msubject)
        sending_msg.set_from(mfrom)
        sending_msg.add_to(mto)
        reposne = sg.send(sending_msg)
        print (reposne)
    else:
        text_content = msubject
        msg = EmailMultiAlternatives(msubject, mbody, mfrom, mto)
        msg.attach_alternative(mbody, "text/html")
        msg.send()