23
Sending emails with python and Twilio-sendgrid API
- Python 3.6 or later
- A free Twilio SendGrid account.
$ mkdir email_sender
$ cd email_sender
$ python3 -m venv venv
$ source venv/bin/activate
After activating the environment, Install the necessary packages:
(venv) $ pip3 install sendgrid
(venv) $ pip3 install sendgrid
NB: the python-dotenv is a Python module that allows you to specify environment variables in traditional UNIX-like “.env” (dot-env) file within your Python project directory. It helps us work with SECRETS and KEYS without exposing them to the outside world, and keep them safe during the development of applications.Read more
SENDGRID_API_KEY="mskj.bjsknlfjlsjnsnsnkjaknkkkwnkakJKkjnkKKNXKBVThdubsckeuisi"
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from dotenv import load_dotenv
load_dotenv()
message = Mail(
from_email='[email protected]',
to_emails='[email protected]',
subject='Sending emails with python and Twilio-sendgrid API',
html_content='<strong>Thankyou for your business</strong>')
try:
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)
python3 app.py
The email arrives to the recipients inbox within seconds
23