Skip to content

Instantly share code, notes, and snippets.

@NorakGithub
Created May 27, 2019 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NorakGithub/ef083ca954a4702b101de4c2614a8572 to your computer and use it in GitHub Desktop.
Save NorakGithub/ef083ca954a4702b101de4c2614a8572 to your computer and use it in GitHub Desktop.
SendGrid Python API Client for Sending Email
import requests
class SendGrid:
def __init__(self, **kwargs):
self.api_key: str = kwargs.get('api_key')
self.subject: str = kwargs.get('subject')
self.sender: str = kwargs.get('sender')
self.receivers: [str] = kwargs.get('receivers')
self.content_type: str = kwargs.get('content_type', 'text/plain')
self.content: str = kwargs.get('content')
def build_json(self):
return {
'personalizations': [
{
'to': [{'email': email} for email in self.receivers],
'subject': self.subject
}
],
'from': {'email': self.sender},
'content': [
{
'type': self.content_type,
'value': self.content,
}
]
}
def send(self):
return requests.post(
url='https://api.sendgrid.com/v3/mail/send',
json=self.build_json(),
headers={
'Content-Type': 'application/json',
'Authorization': f'Bearer {self.api_key}',
}
)
sendgrid = SendGrid(
api_key='SendGridAPIKey',
sender='sender@email.com',
receivers=['receiver@email.com'],
subject='Subject email',
content_type='text/plain',
content='Hello World',
)
response = sendgrid.send()
log.debug(response.status_code)
log.debug(response.content)
log.debug(response.headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment