Created
May 27, 2019 10:13
-
-
Save NorakGithub/ef083ca954a4702b101de4c2614a8572 to your computer and use it in GitHub Desktop.
SendGrid Python API Client for Sending Email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}', | |
} | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sendgrid = SendGrid( | |
api_key='SendGridAPIKey', | |
sender='[email protected]', | |
receivers=['[email protected]'], | |
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