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
A full-featured Python wrapper for the Onfleet API.

UPDATE: Please use Onfleet's wrapper instead. This repository is not maintained. https://github.com/onfleet/pyonfleet --- Python-Onfleet โ€ƒ python-onfl

Lionheart Software 11 Jan 13, 2022
Tiktok 2 Instagram With Python

Tiktok2Instagram ๐Ÿ“ธ About The Project What it does: Download the source video from a user inputted Tiktok URL. ๐Ÿ“™ Add audio to the Tiktok video from a

Carter Belisle 4 Feb 06, 2022
Copier template for solving Advent of Code puzzles with Python

Advent of Code Python Template for Copier This template creates scaffolding for one day of Advent of Code. It includes tests and can download your per

Geir Arne Hjelle 6 Dec 25, 2022
Crypto trading bot that detects surges in the bitcoin price and executes trades.

The bot will be trading Bitcoin automatically if the price has increased by more than 3% in the last 10 minutes. We will have a stop loss of 5% and t

164 Oct 20, 2022
Weather Tracker, made with Python using Open Weather API

Weather Tracker Weather Tracker, made with Python using Open Weather API

Sahil Kumar 1 Feb 07, 2022
Versatile async-friendly library to retry failed operations with configurable backoff strategies

riprova riprova (meaning retry in Italian) is a small, general-purpose and versatile Python library that provides retry mechanisms with multiple backo

Tom 108 Apr 27, 2022
Assassination API for getting random quotes from Assassination Classroom.

Assassination API Take advantage of what you have, while you have it. Quotes from Assassination Classroom Assassination classroom is one of best anime

Swanand Mulay 3 Jul 15, 2022
ServiceX DID Finder Girder

ServiceX_DID_Finder_Girder Access datasets for ServiceX from yt Hub Finding datasets This DID finder is designed to take a collection id (https://gird

1 Dec 07, 2021
Mรฉtamorphose Renamer v2

Mรฉtamorphose 2 Mรฉtamorphose is a graphical mass renaming program for files and folders. These are the command line options: -h, --help Show hel

Mรฉtamorphose 129 Dec 30, 2022
๐Ÿค– The bot that runs the official Fairfield Programming Association Discord server.

๐Ÿค– The bot that runs the official Fairfield Programming Association Discord server.

Fairfield Programming Association 1 Jan 07, 2022
JAWS Pankration 2021 - DDD on AWS Lambda sample

JAWS Pankration 2021 - DDD on AWS Lambda sample What is this project? This project contains sample code for AWS Lambda with domain models. I presented

Atsushi Fukui 21 Mar 30, 2022
Automation that uses Github Actions, Google Drive API, YouTube Data API and youtube-dl together to feed BackJam app with new music

Automation that uses Github Actions, Google Drive API, YouTube Data API and youtube-dl together to feed BackJam app with new music

Antรดnio Oliveira 1 Nov 21, 2021
Python library for the DeepL language translation API.

The DeepL API is a language translation API that allows other computer programs to send texts and documents to DeepL's servers and receive high-quality translations. This opens a whole universe of op

DeepL 535 Jan 04, 2023
This Bot Can Upload Video from Link Of Pdisk to Pdisk using its API. @PredatorHackerzZ

๐๐๐ข๐ฌ๐ค ๐‚๐จ๐ง๐ฏ๐ž๐ซ๐ญ๐ž๐ซ ๐๐จ๐ญ Make short link by using ๐๐๐ข๐ฌ๐ค API key Installation ๐“๐ก๐ž ๐„๐š๐ฌ๐ฒ ๐–๐š๐ฒ ๐‘๐ž๐ช๐ฎ๐ข๐ซ๐ž๐ ๐•๐š๐ซ๐ข๐š๐›๐ฅ๐ž

ฯัั”โˆ‚ฮฑั‚ฯƒั 25 Dec 02, 2022
A twitter bot that simply replies with a beautiful screenshot of the tweet, powered by beautify.dhravya.dev

Poet this! Replies with a beautiful screenshot of the tweet, powered by poet.so Installation git clone https://github.com/dhravya/poet-this.git cd po

Dhravya Shah 30 Dec 04, 2022
Official API documentation for Highrise

Highrise API The Highrise API is implemented as vanilla XML over HTTP using all four verbs (GET/POST/PUT/DELETE). Every resource, like Person, Deal, o

Basecamp 128 Dec 06, 2022
Spodcast is a caching Spotify podcast to RSS proxy

Spodcast Spodcast is a caching Spotify podcast to RSS proxy. Using Spodcast you can follow Spotify-hosted netcasts/podcasts using any player which sup

Frank de Lange 260 Jan 01, 2023
The purpose of this bot is to take soundcloud track requests, that are posted in the stream-requests channel, and add them to a playlist, to make the process of scrolling through the requests easier for Root

Discord Song Collector Dont know if anyone is actually going to read this, but the purpose of this bot is to check every message in the stream-request

2 Mar 01, 2022
Simple PoC script that allows you to exploit telegram's "send with timer" feature by saving any media sent with this functionality.

Simple PoC script that allows you to exploit telegram's "send with timer" feature by saving any media sent with this functionality.

Matteo 52 Nov 29, 2022
Ghost-toolbox - Ghost's official Discord raid tool

Ghost Toolbox Ghost's official Discord raid tool. How to use Clone this repo int

G H ร˜ S T 10 Oct 31, 2022