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
Una herramienta para transmitir mensajes automáticamente a múltiples grupos de chat

chat-broadcast Una herramienta para transmitir mensajes automáticamente a múltiples grupos de chat Setup Librerías Necesitas Python 3 con la librería

Seguimos 2 Jan 09, 2022
SaltConf21: Adding Workflow Approval to Salt

SaltConf21: Adding Workflow Approval to Salt Running To run the example, install Docker and docker-compose and run the following commands: docker-comp

SSYS Sistemas 4 Nov 24, 2021
The Best Telegram UserBot Made With Pyrogram [Python]

Asterix UserBot A Powerful Telegram userbot based on Pyrogram. How To Deploy Asterix Heroku Railway Qovery Termux Tutorial Railway Deploy Comming Soon

TeamAsterix 9 Oct 17, 2022
SIGIT - Simple Information Gathering Toolkit

SIGIT - Simple Information Gathering Toolkit Features userrecon - username reconnaissance facedumper - dump facebook information mailfinder - find ema

Termux Hackers 437 Dec 29, 2022
The best Discord bot, created for r/Jailbreak

Bloo Setup instructions These instructions assume you are on macOS or Linux. Windows users, good luck. With Docker (recommended!) You will need the fo

GIR 33 Dec 16, 2022
Dumps to CSV all the resources in an organization's member accounts

AWS Org Inventory Dumps to CSV all the resources in an organization's member accounts. Set your environment's AWS_PROFILE and AWS_DEFAULT_REGION varia

Iain Samuel McLean Elder 2 Dec 24, 2021
Trading through Binance's API using Python & sqlite

pycrypt Automate trading crypto using Python to pull data from Binance's API and analyse trends. May or may not consistently lose money but oh well it

Maxim 4 Sep 02, 2022
Get Notified about vaccine availability in your location on email & sms ✉️! Vaccinator Octocat tracks & sends personalised vaccine info everday. Go get your shot ! 💉

Vaccinater Get Notified about vaccine availability in your location on email & sms ✉️ ! Vaccinator Octocat tracks & sends personalised vaccine info ev

Mayukh Pankaj 6 Apr 28, 2022
A discord bot that can detect Nitro Scam Links and delete them to protect other users

A discord bot that can detect Nitro Scam Links and delete them to protect other users. Add it to your server from here.

Kanak Mittal 9 Oct 20, 2022
=>|<= the MsgRoom bot for Windows 96

=|= bot A MsgRoom bot in Python 3 for Windows96.net. The bot joins as =|=, if parameter name_lasts is not true and default_name is =|=. The full

Larry Holst 2 Jun 07, 2022
This is telegram bot to generate string session for using user bots. You can see live bot in https://telegram.dog/string_session_Nsbot

TG String Session Generate Pyrogram String Session Using this bot. Demo Bot: Configs: API_HASH Get from Here. API_ID Get from Here. BOT_TOKEN Telegram

Anonymous 27 Oct 28, 2022
Async wrapper over hentaichan.live

hentai-chan-api-async is a small asynchronous parser library that will allow you to easily use manga from https://hentaichan.live Recommended to use python3.7+

7 Dec 15, 2022
Telegram Bot For Screenshot Generation.

Screenshotit_bot Telegram Bot For Screenshot Generation. Description An attempt to implement the screenshot generation of telegram files without downl

1 Nov 06, 2021
Experiment to find the best time to look for an appointment at the Berlin Bürgeramt

Bürgeramt appointment experiment Checks Berlin.de for free Anmeldung appointments every X minutes, then analyses the results. How to use Run get-page.

Nicolas Bouliane 42 Jan 02, 2023
Twitter-bot - A Simple Twitter bot with python

twitterbot To use this bot, You will require API Key and Access Key. Signup at h

Bentil Shadrack 8 Nov 18, 2022
Python library for using SMS.ir web services

smsir smsir is a Python library for using SMS web services www.sms.ir Installation Use the package manager pip to install smsir. pip install smsir Usa

mohammad reza 2 Oct 14, 2022
Discord nuke bot with python

Discord-nuke-bot 🇷🇺 🇷🇺 🇷🇺 🇷🇺 🇷🇺 TODO: Добавить команду: Удаления всех ролей Спама каналами Спама во все каналы @everyone Удаления всего aka

Nikita Maykov 10 Oct 14, 2022
Cyber Userbot

Cyber Userbot

Irham 0 May 26, 2022
a simple quant trading bot with CLI interface

shepherd a simple quant trading bot with CLI interface CLI shell command docs coming soon after I brush up the code and add more features :) Minimal R

m00n 0 Jun 06, 2022