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 Python package that can be used to download post and comment data from Reddit.

Reddit Data Collector Reddit Data Collector is a Python package that allows a user to collect post and comment data from Reddit. It is built on top of

Nico Van den Hooff 3 Jul 26, 2022
A telegram bot to interact with a Minecraft Server

telegram-mc-bot A telegram bot to interact with a Minecraft Server It has the following commands: /status - Returns the server status (Online/Offline)

KleynArt 1 Dec 09, 2021
A demo without 🚀 science, just simple UTXO spending logic.

Stuck TX Demo Docker container that runs 4 dogecoind to demonstrate "the stuck tx problem". Scenario A wallet sends out 3 transactions to a recipient

Patrick Lodder 2 Nov 16, 2021
Grade Notifyer Bot

A bot that automatically crawl the submission platform of montefiore to notify the student when a project has been graded.

Julien Gustin 2 Jun 02, 2022
Represents a Lavalink client used to manage nodes and connections.

lavaplayer Represents a Lavalink client used to manage nodes and connections. setup pip install lavaplayer setup lavalink you need to java 11* LTS or

HazemMeqdad 37 Nov 21, 2022
TFT Bot that automatically surrenders and allows finishing TFT Passes easily.

Image Based TFT Bot TFT Bot that automatically surrenders and allows finishing TFT Passes easily. Please read full file! You can check new releases he

1 Feb 06, 2022
A python SDK for interacting with quantum devices on Amazon Braket

Amazon Braket Python SDK The Amazon Braket Python SDK is an open source library that provides a framework that you can use to interact with quantum co

Amazon Web Services 213 Dec 14, 2022
A cracking tool of Xiaomi Dr AI (Archytas / Archimedes)

Archytas Tool 我们强烈抵制闲鱼平台上未经授权的刷机服务! 我对本人之前在程序中为防止违规刷机服务添加未生效的格机代码感到抱歉,在此声明此过激行为与 Crack Mi Dr AI Team 无关,并将程序开源。 A cracking tool of Xiaomi Dr AI (Archy

rponeawa 5 Oct 25, 2022
Yes, it's true :orange_heart: This repository has 346 stars.

Yes, it's true! Inspired by a similar repository from @RealPeha, but implemented using a webhook on AWS Lambda and API Gateway, so it's serverless! If

512 Jan 01, 2023
A napari plugin for visualising and interacting with electron cryotomograms

napari-subboxer A napari plugin for visualising and interacting with electron cryotomograms. Installation You can install napari-subboxer via pip: pip

3 Nov 25, 2021
My attempt at weaponizing Discord.

MayorbotC2 This is my Discord C2 bot. There are many like it, but this one is mine. MayorbotC2 is a project I absolutely forgot about until I was pilf

Joe Helle 19 May 16, 2022
An API that uses NLP and AI to let you predict possible diseases and symptoms based on a prompt of what you're feeling.

Disease detection API for MediSearch An API that uses NLP and AI to let you predict possible diseases and symptoms based on a prompt of what you're fe

Sebastian Ponce 1 Jan 15, 2022
Administration Panel for Control FiveM Servers From Discord

FiveM Discord Administration Panel Version 1.0.0 If you would like to report an issue or request a feature. Join our Discord or create an issue. Contr

NIma 9 Jun 17, 2022
Balanced API library in python.

Balanced Online Marketplace Payments v1.x requires Balanced API 1.1. Use v0.x for Balanced API 1.0. Installation pip install balanced Usage View Bala

Balanced 70 Oct 04, 2022
Python script to replace BTC adresses in the clipboard with similar looking ones, whose private key can be retrieved by a netcat listener or similar.

BTCStealer Python script to replace BTC adresses in the clipboard with similar looking ones, whose private key can be retrieved by a netcat listener o

Some Person 6 Jun 07, 2022
Many discord bots serving different purposes

Discord_Botlari Farklı amaçlara hizmet eden bir çok discord botu En kapsamlı Bot Game Bottur. bir oyun botudur discord sunucularında kullanılır. (tüm

1 Dec 21, 2021
✨ A simple project to automate some stuffs in Habbo with G-Earth ✨

⚡️ Habbo G-Earth extensions ⚡️ ✨ A simple project to automate some stuffs in Habbo with G-Earth ✨ About | Getting Started | Authors ➤ Getting Started

Lucca Pessoa 1 Jan 09, 2022
❝𝐓𝐡𝐞 𝐌𝐨𝐬𝐭 𝐏𝐨𝐰𝐞𝐫𝐟𝐮𝐥𝐥 𝐆𝐫𝐨𝐮𝐩 𝐌𝐚𝐧𝐚𝐠𝐞𝐦𝐞𝐧𝐭 𝐁𝐨𝐭❞

❝𝐓𝐡𝐞 𝐌𝐨𝐬𝐭 𝐏𝐨𝐰𝐞𝐫𝐟𝐮𝐥𝐥 𝐆𝐫𝐨𝐮𝐩 𝐌𝐚𝐧𝐚𝐠𝐞𝐦𝐞𝐧𝐭 𝐁𝐨𝐭❞

Abdisamad Omar Mohamed 5 Jun 24, 2022
Stock market bot that will be used to learn about API calls and database connections.

Stock market bot that will be used to learn about API calls and database connections.

1 Dec 24, 2021
⚡️ Get notified as soon as your next CPU, GPU, or game console is in stock

Inventory Hunter This bot helped me snag an RTX 3070... hopefully it will help you get your hands on your next CPU, GPU, or game console. Requirements

Eric Marti 1.1k Dec 26, 2022