The sendgrid
package provides some useful emailing capabilities via the SendGrid Email Delivery Service. 📬 ✉️
Reference:
- Source
- Package
- Example Usage
- Heroku's SendGrid Guide
- SendGrid Account Types, including Free Tier
- SendGrid Account Signup
- Obtaining API Keys
Install sendgrid
, if necessary:
pip install sendgrid
First, sign up for a free account, then click the link in a confirmation email to verify your account. Then create an API Key with "full access" permissions.
To setup the usage example below, store the API Key value in an environment variable called SENDGRID_API_KEY
. Also set an environment variable called MY_EMAIL_ADDRESS
to be the email address you just associated with your SendGrid account (e.g. "abc123@gmail.com").
Send yourself an email:
import os
from dotenv import load_dotenv
import sendgrid
from sendgrid.helpers.mail import * # source of Email, Content, Mail, etc.
load_dotenv()
SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY", "OOPS, please set env var called 'SENDGRID_API_KEY'")
MY_EMAIL_ADDRESS = os.environ.get("MY_EMAIL_ADDRESS", "OOPS, please set env var called 'MY_EMAIL_ADDRESS'")
# AUTHENTICATE
sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
# COMPILE REQUEST PARAMETERS (PREPARE THE EMAIL)
from_email = Email(MY_EMAIL_ADDRESS)
to_email = Email(MY_EMAIL_ADDRESS)
subject = "Hello World from the SendGrid Python Library!"
content = Content("text/plain", "Hello, Email!")
mail = Mail(from_email, subject, to_email, content)
# ISSUE REQUEST (SEND EMAIL)
response = sg.client.mail.send.post(request_body=mail.get())
# PARSE RESPONSE
print(response.status_code) #> 202 means success
print(response.body) #> this might be empty. it's ok.
print(response.headers)