This library allows you to quickly and easily send emails through SendGrid using Python.
If you upgrade to version 1.2.x
, the add_to
method behaves differently. In the past this method defaulted to using the SMTPAPI
header. Now you must explicitly call the smtpapi.add_to
method. More on the SMTPAPI
section.
For users of our Web API v3 endpoints, we have begun integrating v3 endpoints into this library. As part of this process we have implemented a test automation tool, TOX. We are also updating and enhancing the core library code.
In no particular order, we have implemented a few of the v3 endpoints already and would appreciate your feedback.
Thank you for your continued support!
To use the SendGrid Web API, you will need an API Key. You can create one in your SendGrid Dashboard.
pip install sendgrid
# or
easy_install sendgrid
import sendgrid
sg = sendgrid.SendGridClient('YOUR_SENDGRID_API_KEY')
message = sendgrid.Mail()
message.add_to('John Doe <john@email.com>')
message.set_subject('Example')
message.set_html('Body')
message.set_text('Body')
message.set_from('Doe John <doe@email.com>')
status, msg = sg.send(message)
#or
message = sendgrid.Mail(to='john@email.com', subject='Example', html='Body', text='Body', from_email='doe@email.com')
status, msg = sg.send(message)
By default, .send
method returns a tuple (http_status_code, message)
,
however you can pass raise_errors=True
to SendGridClient
constructor,
then .send
method will raise SendGridClientError
for 4xx errors,
and SendGridServerError
for 5xx errors.
from sendgrid import SendGridError, SendGridClientError, SendGridServerError
sg = sendgrid.SendGridClient('YOUR_SENDGRID_API_KEY', None, raise_errors=True)
try:
sg.send(message)
except SendGridClientError:
...
except SendGridServerError:
...
This behavior is going to be default from version 2.0.0. You are
encouraged to set raise_errors
to True
for forwards compatibility.
SendGridError
is a base-class for all SendGrid-related exceptions.
To begin using this library create a new instance of SendGridClient with your SendGrid API Key. To configure API keys, visit https://app.sendgrid.com/settings/api_keys.
sg = sendgrid.SendGridClient('YOUR_SENDGRID_API_KEY')
There are multiple ways to add recipients:
message = sendgrid.Mail()
message.add_to('example@email.com')
# or
message.add_to('Example Dude <example@email.com>')
# or
message.add_to(['Example Dude <example@email.com>', 'john@email.com'])
message = sendgrid.Mail()
message.add_to('example@email.com')
message.add_to_name('Example Dude')
message = sendgrid.Mail()
message.add_cc('example@email.com')
message.add_cc(['example@email.com', 'john@email.com'])
message = sendgrid.Mail()
message.add_bcc('example@email.com')
# or
message.add_bcc(['Example Dude <example@email.com>', 'john@email.com'])
message = sendgrid.Mail()
message.set_from('example@email.com')
message = sendgrid.Mail()
message.set_from('example@email.com')
message.set_from_name('Example Dude')
message.sendgrid.Mail()
message.set_replyto('example@email.com')
message = sendgrid.Mail()
message.set_subject('Example')
message = sendgrid.Mail()
message.set_text('Body')
message = sendgrid.Mail()
message.set_html('<html><body>Stuff, you know?</body></html>')
message = sendgrid.Mail()
message.set_date('Wed, 17 Dec 2014 19:21:16 +0000')
message = sendgrid.Mail()
message.set_headers({'X-Sent-Using': 'SendGrid-API', 'X-Transport': 'web'});
There are multiple ways to work with attachments:
message = sendgrid.Mail()
message.add_attachment('stuff.txt', './stuff.txt')
# or
message.add_attachment('stuff.txt', open('./stuff.txt', 'rb'))
message = sendgrid.Mail()
message.add_attachment_stream('filename', 'somerandomcontentyouwant')
# strings, unicode, or BytesIO streams
message = sendgrid.Mail()
message.add_attachment('image.png', open('./image.png', 'rb'))
message.add_content_id('image.png', 'ID_IN_HTML')
message.set_html('<html><body>TEXT BEFORE IMAGE<img src="cid:ID_IN_HTML"></img>AFTER IMAGE</body></html>')
To use the SendGrid Web API v3, you will need an API Key. You can create one in your SendGrid Dashboard.
List all API Keys belonging to the authenticated user.
client = sendgrid.SendGridAPIClient('SENDGRID_API_KEY')
status, msg = client.apikeys.get()
Generate a new API Key for the authenticated user
client = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
name = "My Amazing API Key"
status, msg = client.apikeys.post(name)
Revoke an existing API Key
client = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
status, msg = client.apikeys.delete(api_key_id)
Update the name of an existing API Key
client = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
name = "My NEW API Key 3000"
status, msg = client.apikeys.patch(api_key_id, name)
Unsubscribe Manager gives your recipients more control over the types of emails they want to receive by letting them opt out of messages from a certain type of email.
Retrieve all suppression groups associated with the user.
client = sendgrid.SendGridAPIClient('SENDGRID_API_KEY')
status, msg = client.asm_groups.get()
Get a single record.
status, msg = client.asm_groups.get(record_id)
Create a new suppression group.
status, msg = client.asm_groups.post(name, description, is_default)
Suppressions are email addresses that can be added to groups to prevent certain types of emails from being delivered to those addresses.
Add recipient addresses to the suppressions list for a given group.
client = sendgrid.SendGridAPIClient('SENDGRID_API_KEY')
group_id = <group_id_number> # If no group_id_number, the emails will be added to the global suppression group
emails = ['example@example.com', 'example@example.com']
status, msg = client.asm_suppressions.post(group_id, emails)
Get suppressed addresses for a given group.
status, msg = client.asm_suppressions.get(<group_id>)
Delete a recipient email from the suppressions list for a group.
status, msg = client.asm_suppressions.delete(<group_id>,<email_address>)
Global Suppressions are email addresses that will not receive any emails.
Check if a given email is on the global suppression list.
client = sendgrid.SendGridAPIClient('SENDGRID_API_KEY')
email = ['example@example.com']
status, msg = client.asm_global_suppressions.get(email)
Get a list of all SendGrid globally unsubscribed emails.
Add an email to the global suppression list.
Delete an email from the global suppression list.
Global Stats provide all of your user's email statistics for a given date range.
SendGrid's X-SMTPAPI
If you wish to use the X-SMTPAPI on your own app, you can use the SMTPAPI Python library.
There are implementations for setter methods too.
sg = sendgrid.SendGridClient('SENDGRID_API_KEY')
message = sendgrid.Mail()
message.add_substitution(':first_name', 'John')
message.smtpapi.add_to('John <example@example.com>')
message.set_subject('Testing from the Python library using the SMTPAPI')
message.set_html('<b>:first_name, this was a successful test of using the SMTPAPI library!</b>')
message.set_text(':name, this was a successful test of using the SMTPAPI library!')
message.set_from('Jane <example@example.com>')
sg.send(message)
message = sendgrid.Mail()
message.smtpapi.add_to('example@email.com')
message = sendgrid.Mail()
message.smtpapi.add_substitution('key', 'value')
message = sendgrid.Mail()
message.add_substitution('key', 'value')
message = sendgrid.Mail()
message.set_substitutions({'key1': ['value1', 'value2'], 'key2': ['value3', 'value4']})
message = sendgrid.Mail()
message.smtpapi.add_section('section', 'value')
message = sendgrid.Mail()
message.add_section('section', 'value')
message = sendgrid.Mail()
message.set_sections({'section1': 'value1', 'section2': 'value2'})
message = sendgrid.Mail()
message.smtpapi.add_category('category')
message = sendgrid.Mail()
message.add_category('category')
message = sendgrid.Mail()
message.set_categories(['category1', 'category2'])
message = sendgrid.Mail()
message.smtpapi.add_unique_arg('key', 'value')
message = sendgrid.Mail()
message.add_unique_arg('key', 'value')
message = sendgrid.Mail()
message.set_unique_args({'key1': 'value1', 'key2': 'value2'})
message = sendgrid.Mail()
message.smtpapi.add_filter('filter', 'setting', 'value')
message = sendgrid.Mail()
message.add_filter('filter', 'setting', 'value')
message = sendgrid.Mail()
message.smtpapi.set_asm_group_id(value)
message = sendgrid.Mail()
message.set_asm_group_id(value)
message.add_filter('templates', 'enable', '1')
message.add_filter('templates', 'template_id', 'TEMPLATE-ALPHA-NUMERIC-ID')
message.add_substitution('key', 'value')
Prerequisites:
- Mac OS X Prerequisite:
xcode-select --install
- Install pyenv and tox
brew update
brew install pyenv
pip install tox
- Add eval "$(pyenv init -)" to your profile after installing tox, you only need to do this once.
pyenv install 2.6.9
pyenv install 2.7.8
pyenv install 3.2.6
pyenv install 3.3.6
pyenv install 3.4.3
pyenv install 3.5.0
Run the tests:
virtualenv venv
source venv/bin/activate #or . ./activate.sh
python setup.py install
pyenv local 3.5.0 3.4.3 3.3.6 3.2.6 2.7.8 2.6.9
pyenv rehash
tox
- Confirm tests pass
- Bump the version in sendgrid/version.py
- Update CHANGELOG.md
- Confirm tests pass
- Commit Version bump vX.X.X
- python setup.py sdist bdist_wininst upload
- Push changes to GitHub
- Release tag on GitHub vX.X.X