The Official Twilio SendGrid Led, Community Driven Python API Library

Overview

SendGrid Logo

Travis Badge codecov Docker Badge Email Notifications Badge MIT licensed Twitter Follow GitHub contributors Open Source Helpers

The default branch name for this repository has been changed to main as of 07/27/2020.

This library allows you to quickly and easily use the SendGrid Web API v3 via Python.

Version 3.X.X+ of this library provides full support for all SendGrid Web API v3 endpoints, including the new v3 /mail/send.

This library represents the beginning of a new path for SendGrid. We want this library to be community driven and SendGrid led. We need your help to realize this goal. To help make sure we are building the right things in the right order, we ask that you create issues and pull requests or simply upvote or comment on existing issues or pull requests.

Please browse the rest of this README for further detail.

We appreciate your continued support, thank you!

Table of Contents

Installation

Prerequisites

  • Python version 2.7, 3.5, 3.6, 3.7, or 3.8
  • The SendGrid service, starting at the free level

Setup Environment Variables

Mac

Update the development environment with your SENDGRID_API_KEY (more info here), for example:

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

SendGrid also supports local environment file .env. Copy or rename .env_sample into .env and update SENDGRID_API_KEY with your key.

Windows

Temporarily set the environment variable(accessible only during the current cli session):

set SENDGRID_API_KEY=YOUR_API_KEY

Permanently set the environment variable(accessible in all subsequent cli sessions):

setx SENDGRID_API_KEY "YOUR_API_KEY"

Install Package

pip install sendgrid

Dependencies

Quick Start

Hello Email

The following is the minimum needed code to send an email with the /mail/send Helper (here is a full example):

With Mail Helper Class

import sendgrid
import os
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("[email protected]")
to_email = To("[email protected]")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, to_email, subject, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)

The Mail constructor creates a personalization object for you. Here is an example of how to add it.

Without Mail Helper Class

The following is the minimum needed code to send an email without the /mail/send Helper (here is a full example):

import sendgrid
import os

sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
data = {
  "personalizations": [
    {
      "to": [
        {
          "email": "[email protected]"
        }
      ],
      "subject": "Sending with SendGrid is Fun"
    }
  ],
  "from": {
    "email": "[email protected]"
  },
  "content": [
    {
      "type": "text/plain",
      "value": "and easy to do anywhere, even with Python"
    }
  ]
}
response = sg.client.mail.send.post(request_body=data)
print(response.status_code)
print(response.body)
print(response.headers)

General v3 Web API Usage (With Fluent Interface)

import sendgrid
import os

sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
response = sg.client.suppression.bounces.get()
print(response.status_code)
print(response.body)
print(response.headers)

General v3 Web API Usage (Without Fluent Interface)

import sendgrid
import os

sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
response = sg.client._("suppression/bounces").get()
print(response.status_code)
print(response.body)
print(response.headers)

Processing Inbound Email

Please see our helper for utilizing our Inbound Parse webhook.

Usage

Use Cases

Examples of common API use cases, such as how to send an email with a transactional template.

Announcements

Please see our announcement regarding breaking changes. Your support is appreciated!

All updates to this library are documented in our CHANGELOG and releases. You may also subscribe to email release notifications for releases and breaking changes.

How to Contribute

We encourage contribution to our libraries (you might even score some nifty swag), please see our CONTRIBUTING guide for details.

Quick links:

Troubleshooting

Please see our troubleshooting guide for common library issues.

About

sendgrid-python is maintained and funded by Twilio SendGrid, Inc. The names and logos for sendgrid-python are trademarks of Twilio SendGrid, Inc.

If you need help installing or using the library, please check the Twilio SendGrid Support Help Center.

If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!

License

The MIT License (MIT)

Comments
  • Proper MIMEMultipart determination for smtp

    Proper MIMEMultipart determination for smtp

    For compatibility with most email clients, you cannot simply detail the message MIME as a MIMEMultipart-Alternative if you have embedded images and attachments for view within HTML. MIMEMultipart-Related is the correct format, per http://tools.ietf.org/html/rfc2387.

    I have tested this with GMail, Thunderbird and Mail.app (Mac client), and it seems to work, whereas the current code will simply display my image attachment and none of the HMTL in Mail.app and Thunderbird.

    opened by vhmth 19
  • Python style fixes

    Python style fixes

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • Cleans up Mail helper: reduces line count, uses Pythonic defaults
    • See commit notes for categories of fixes.

    These things were just bugging me a bit. There's probably a "terser is better" or something in the Python Zen.

    Note: I think existing tests should cover this since I didn't change any functionality, but I'll let Codecov yell at me if not. Tests pass with tox.

    status: code review request difficulty: medium 
    opened by gabrielkrell 15
  • Add Changelog script

    Add Changelog script

    Resolves #693

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • This PR introduces a generate_changelog.sh script that should take the newest PRs that have not been part of the latest release and creates an entry for them in the CHANGELOG.md file.
    • This uses the free, unauthenticated Github api to get PR titles. I felt like this was okay since it was the simplest solution and they allow 60 requests per hour this way.

    Example usage and output:

    ./generate_changelog.sh -v 6.0.0 -t 59077e7424629898d6554bc6a0ddcbd768901ae2
    Getting title of PR #656
    Getting title of PR #636
    Getting title of PR #628
    Getting title of PR #613
    Getting title of PR #619
    Getting title of PR #616
    Getting title of PR #611
    Successfully wrote to CHANGELOG.md
    

    diff

    diff --git a/CHANGELOG.md b/CHANGELOG.md
    index dd2334b..ad57211 100644
    --- a/CHANGELOG.md
    +++ b/CHANGELOG.md
    @@ -1,5 +1,15 @@
     # Change Log
     All notable changes to this project will be documented in this file.
    +## [6.0.0] - 2018-10-19 ##
    +### Added
    +- [PR #656](https://github.com/sendgrid/sendgrid-python/pull/656): Fix helper mail_example redirection link
    +- [PR #636](https://github.com/sendgrid/sendgrid-python/pull/636): Fix broken link for mail example
    +- [PR #628](https://github.com/sendgrid/sendgrid-python/pull/628): Update README
    +- [PR #613](https://github.com/sendgrid/sendgrid-python/pull/613): Update README.md by including email
    +- [PR #619](https://github.com/sendgrid/sendgrid-python/pull/619): Fix format of dependency `pytest`
    +- [PR #616](https://github.com/sendgrid/sendgrid-python/pull/616): Fix typos
    +- [PR #611](https://github.com/sendgrid/sendgrid-python/pull/611): fixes #610
    +
     
     ## [5.6.0] - 2018-08-20 ##
     ### Added
    

    If you have questions, please send an email to SendGrid, or file a GitHub Issue in this repository.

    status: work in progress difficulty: hard type: twilio enhancement 
    opened by PatOConnor43 13
  • feat: Support for AMP HTML Email

    feat: Support for AMP HTML Email

    I acknowledge that my contributions will be made under the same open-source license that the open-source project is provided under

    Adds support for sending AMP HTML email

    • Added third mime type -> text/x-amp-html
    • Send AMP HTML email just like normal html/plain email

    Resolves

    • Fixes #940
    • Fixes #850

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the Contribution Guidelines and my PR follows them
    • [x] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added the necessary documentation about the functionality in the appropriate .md file
    • [x] I have added inline documentation to the code I modified
    type: community enhancement status: waiting for feedback 
    opened by modernwarfareuplink 10
  • Separate Attribution links in CoC #671

    Separate Attribution links in CoC #671

    Signed-off-by: Skchoudhary [email protected]

    Fixes # 671

    Checklist

    • [ ] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [X] I have read the [Contribution Guide] and my PR follows them.
    • [X] I updated my branch with the master branch.
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • separate the link for Open Source Initiative General Code of Conduct and Apache Code of Conduct to appear on the different line.

    If you have questions, please send an email to SendGrid, or file a GitHub Issue in this repository.

    difficulty: easy type: docs update status: waiting for feedback 
    opened by Skchoudhary 10
  • Update CONTRIBUTING.md to add python version 3.6

    Update CONTRIBUTING.md to add python version 3.6

    Fixes #657

    Checklist

    • [X] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [X] I have read the [Contribution Guide] and my PR follows them.
    • [X] I updated my branch with the master branch.
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [X] I have added necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • Update CONTRIBUTING.md to keep instructions updated according to commands to test project

    If you have questions, please send an email to SendGrid, or file a GitHub Issue in this repository.

    type: bug difficulty: easy status: waiting for feedback 
    opened by mosesmeirelles 10
  • docs: Updated link to direct to #L9

    docs: Updated link to direct to #L9

    @misterdorm The link to /mail/send Helper looked fine. Please provide details as to where it should direct to.

    Fixes #633

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • Made changes to #633

    If you have questions, please send an email to SendGrid, or file a GitHub Issue in this repository.

    difficulty: easy type: docs update status: waiting for feedback 
    opened by vinayak42 9
  • Adding events consumer which provides an example of working with email events

    Adding events consumer which provides an example of working with email events

    Resolves #649

    Checklist

    • [ ] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [ ] I have read the [Contribution Guide] and my PR follows them.
    • [ ] I updated my branch with the master branch.
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added in line documentation to the code I modified

    Short description of what this PR does:

    This PR adds

    • A Dockerized Flask app which provides an example of working with email events
    • A readme with guides for
      • Deploying locally with test data
      • Deploying locally with real data (using ngrok)
      • Deploying to Heroku

    This repo already contains a Procfile for the email ingress example, so I've suggested copying the events/ dir into a new repo on the users computer as part of the Heroku deploy to keep them separate.

    status: invalid difficulty: very hard type: twilio enhancement 
    opened by Taiters 9
  • Adds support for dynamic template data in personalizations

    Adds support for dynamic template data in personalizations

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    Adds support for dynamic templates

    Fixes #591

    type: community enhancement status: work in progress difficulty: medium 
    opened by 3lnc 9
  • Initial version of code for supporting API rate limiting - WIP

    Initial version of code for supporting API rate limiting - WIP

    This PR is for initial code review and is still WIP. Will add more commits based on the feedback and answers from maintainers for few of my questions.

    Fixes #249

    • Added variables rate_limit_retry, rate_limit_sleep, RATE_LIMIT_RESPONSE_CODE in the constructor of SendGridAPIClient class.
    • Added method attempt in the class SendGridAPIClient
    • Added initial test file named test_rate_limit.py which calls attempt method.

    @thinkingserious I had a couple of questions while implementing and put up those questions as single line comments in the code - I hope to get advise or answers to those questions

    Thanks

    difficulty: medium status: waiting for feedback 
    opened by waseem18 9
  • Update docstrings/pydoc/help (#170)

    Update docstrings/pydoc/help (#170)

    Add docstrings in main package, helpers. Now things will show up nicely when people show documentation in their editor, use help, or use pydoc to browse the documentation in HTML form.

    Downside: much of the Mail helper docs are copied from the v3 docs, which isn't great for maintainability. I think it'd be too unapproachable just to say "read the docs", and linking docs updates to these docstrings would be a lot of work for the rewards. Maybe a future automation candidate though :)

    Example output:

    Pop-up docs in editors: image

    pydoc HTML: image

    Package-level help:

    >>> import sendgrid
    >>> help(sendgrid)
    Help on package sendgrid:
    
    NAME
        sendgrid
    
    DESCRIPTION
        This library allows you to quickly and easily use the SendGrid Web API v3 via
        Python.
    
        For more information on this library, see the README on Github.
            http://github.com/sendgrid/sendgrid-python
        For more information on the SendGrid v3 API, see the v3 docs:
            http://sendgrid.com/docs/API_Reference/api_v3.html
        For the user guide, code examples, and more, visit the main docs page:
            http://sendgrid.com/docs/index.html
    
        Available subpackages
        ---------------------
        helpers
            Modules to help with common tasks.
    
    PACKAGE CONTENTS
        helpers (package)
        sendgrid
        version
    -- More  --
    

    And individual classes:

    >>> from sendgrid.helpers.mail import Mail
    >>> help(Mail)
    Help on class Mail in module sendgrid.helpers.mail.mail:
    
    class Mail(builtins.object)
     |  A request to be sent with the SendGrid v3 Mail Send API (v3/mail/send).
     |
     |  Use get() to get the request body.
     |
     |  Methods defined here:
    -- More  --
    
    status: code review request difficulty: hard 
    opened by gabrielkrell 9
  • Add Python 3.11 to the testing

    Add Python 3.11 to the testing

    Fixes

    A short description of what this PR does.

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [ ] I have read the Contribution Guidelines and my PR follows them
    • [ ] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added the necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added inline documentation to the code I modified

    If you have questions, please file a support ticket.

    opened by cclauss 0
  • docs: Update webhook auth docstring

    docs: Update webhook auth docstring

    Fixes

    The verify_signature method returns False if the event payload is decoded using utf-8 and special characters exist, such as "é". The payload must be decoded using latin-1 to successfully pass authorization in these situations.

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the Contribution Guidelines and my PR follows them
    • [x] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added the necessary documentation about the functionality in the appropriate .md file
    • [x] I have added inline documentation to the code I modified

    If you have questions, please file a support ticket, or create a GitHub Issue in this repository.

    type: community enhancement type: docs update status: ready for deploy 
    opened by jpclark6 0
Releases(6.9.7)
Owner
Twilio SendGrid
Official open source libraries - send emails and integrate with our APIs fast.
Twilio SendGrid
Python Wrapper for aztro - The Astrology API | Get Daily Horoscope 💫

PyAztro PyAztro is a client library for aztro written in Python. aztro provides horoscope info for sun signs such as Lucky Number, Lucky Color, Mood,

Sameer Kumar 30 Jan 08, 2023
PS3API - PS3 API for TMAPI and CCAPI in python.

PS3API PS3 API for TMAPI and CCAPI in python. Examples Connecting and Attaching from ps3api import PS3API PS3 = PS3API(PS3API.API_TMAPI) if PS3.Conn

Adam 9 Sep 01, 2022
Custom bot I've made to host events on my personal Discord server.

discord_events Custom bot I've made to host events on my personal Discord server. You can try the bot out in my personal server here: https://discord.

AlexFlipnote 5 Mar 16, 2022
Using AWS Batch jobs to bulk copy/sync files in S3

Using AWS Batch jobs to bulk copy/sync files in S3

AWS Samples 14 Sep 19, 2022
A bot that downloads all the necessary files from WeLearn and lists your assignments, filter due assignments, etc.

Welearn-bot This is a bot which lets you interact with WeLearn from the command line. It can Download all files/resources from your courses and organi

Parth Bibekar 17 Oct 19, 2022
🔍 Google Search unofficial API for Python with no external dependencies

Python Google Search API Unofficial Google Search API for Python. It uses web scraping in the background and is compatible with both Python 2 and 3. W

Avi Aryan 204 Dec 28, 2022
⚡ Yuriko Robot ⚡ - A Powerful, Smart And Simple Group Manager Written with AioGram , Pyrogram and Telethon

⚡ Yuriko Robot ⚡ - A Powerful, Smart And Simple Group Manager Written with AioGram , Pyrogram and Telethon

Øғғɪᴄɪᴀʟ Ⱡᴏɢ [₳ғᴋ] 1 Apr 01, 2022
An example of a chatbot with a number-based menu that can be used as a starting point for a project.

NumMenu Bot NumMenu Bot is an example chatbot showing a way to design a number-based menu assistant with Rasa. This type of bot is very useful on plat

Derguene 19 Nov 14, 2022
Transcript-Extractor-Bot - Yet another Telegram Voice Recognition bot but using vosk and supports 20+ languages

transcript extractor Yet another Telegram Voice Recognition bot but using vosk a

6 Oct 21, 2022
Code for "Multimodal Trajectory Prediction Conditioned on Lane-Graph Traversals," CoRL 2021.

Multimodal Trajectory Prediction Conditioned on Lane-Graph Traversals This repository contains code for "Multimodal trajectory prediction conditioned

Nachiket Deo 113 Dec 28, 2022
This repository is used to simplify the process of cloning the SSM documents across the AWS regions.

SSM Cloner Introduction This module is created in order to simplify the process of copying the SSM documents from one region to another regions. As an

6 Jun 04, 2022
The scope of this project will be to build a data ware house on Google Cloud Platform that will help answer common business questions as well as powering dashboards

The scope of this project will be to build a data ware house on Google Cloud Platform that will help answer common business questions as well as powering dashboards.

Shweta_kumawat 2 Jan 20, 2022
Riffdog Terraform scanner - finding 'things' in the Real World (aka AWS) which Terraform didn't put there.

riffdog Riffdog Terraform / Reality scanner - finding 'things' in the Real World which Terraform didn't put there. This project works by firstly loadi

Riffdog 4 Mar 23, 2020
An unofficial API for lyricsfreak.com using django and django rest framework.

An unofficial API for lyricsfreak.com using django and django rest framework.

Hesam Norin 1 Feb 09, 2022
A Bot to Track Kernel Upstreams from kernel.org and Post it on Telegram Channel

Channel Kernel Tracker is the channel where the bot will be sending the updates in. Introduction This is a Telegram Bot to Track Kernel Upstreams kern

Kartikeya Hegde 3 Oct 05, 2021
PyHoroscope - Observational Indian lunisolar calendar, horoscope and matching using the Swiss ephemeris

PyHoroscope Observational Indian lunisolar calendar, horoscope and matching usin

4 Jun 05, 2022
A Discord bot to allow people to create lists of random characters, with limit reroll options.

Mugen Bot A small bot I made to practice python and allow people to publically select random characters on a discord server. Uses py-cord, as that is

Haley 2 Feb 06, 2022
SOLSEA-NFT-EXPLORE - Using Streamlit to build a simple UI on top of the Solana API

SOLSEA NFT Explorer Using Streamlit to build a simple UI on top of the Solana AP

Devin Capriola 3 Mar 19, 2022
Leakvertise is a Python open-source project which aims to bypass these fucking annoying captchas and ads from linkvertise, easily

Leakvertise Leakvertise is a Python open-source project which aims to bypass these fucking annoying captchas and ads from linkvertise, easily. You can

Quatrecentquatre 9 Oct 06, 2022
Simple Self-Bot for Discord

KeunoBot 🐼 -Simple Self-Bot for Discord KEUNOBOT 🐼 - Run KeunoBot : /* - Install KeunoBot - Extract it - Run setup.bat - Set token and prefi

Bidouffe 2 Mar 10, 2022