該程式庫可讓您透過 Python 快速輕鬆地使用 SendGrid Web API v3。
該庫的 3.X.X+ 版本為所有 SendGrid Web API v3 端點提供全面支持,包括新的 v3 /mail/send。
該庫代表了 SendGrid 新路徑的開始。我們希望這個函式庫由社群驅動並由 SendGrid 主導。我們需要您的幫助來實現這一目標。為了幫助確保我們以正確的順序建立正確的內容,我們要求您建立問題和拉取請求,或只是對現有問題或拉取請求進行投票或評論。
如果您需要使用 SendGrid 的協助,請查看 Twilio SendGrid 支援協助中心。
請瀏覽本自述文件的其餘部分以獲取更多詳細資訊。
使用您的 SENDGRID_API_KEY 更新開發環境(更多資訊請參閱此處),例如:
echo " export SENDGRID_API_KEY='YOUR_API_KEY' " > sendgrid.env
echo " sendgrid.env " >> .gitignore
source ./sendgrid.env
SendGrid 也支援本機環境檔案.env
。將.env_sample
複製或重新命名為.env
並使用您的金鑰更新 SENDGRID_API_KEY。
暫時設定環境變數(僅在當前 cli 會話期間可存取):
set SENDGRID_API_KEY=YOUR_API_KEY
永久設定環境變數(可在所有後續 cli 會話中存取):
setx SENDGRID_API_KEY " YOUR_API_KEY "
pip install sendgrid
以下是使用 /mail/send Helper 發送電子郵件所需的最少程式碼(這是一個完整的範例):
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 )
Mail
建構函式為您建立一個個人化物件。這是如何添加它的範例。
以下是在沒有 /mail/send Helper 的情況下發送電子郵件所需的最少程式碼(這是一個完整的範例):
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 )
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 )
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 )
請參閱我們的說明程式以了解如何使用我們的入站解析 webhook。
常見 API 案例的範例,例如如何使用事務範本傳送電子郵件。
該程式庫的所有更新都記錄在我們的變更日誌和版本中。
我們鼓勵為我們的圖書館做出貢獻(您甚至可能會獲得一些漂亮的禮物),請參閱我們的貢獻指南以了解詳細資訊。
快速連結:
請參閱我們的常見函式庫問題故障排除指南。
sendgrid-python 由 Twilio SendGrid, Inc. 維護和資助。
如果您需要支持,請查看 Twilio SendGrid 支援幫助中心。
麻省理工學院許可證 (MIT)