Table of Contents

How to setup SendGrid Email Service on Unix

Before you setup SendGrid, you need to setup Twilio, Follow the tutorial how to setup Twilio

Once Twilio is seup, we can install SendGrid using pip

pip install sendgrid
echo "export SENDGRID_API_KEY='api_key'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
echo 'source ./sendgrid.env' >> ~/.zshrc

Thats it now you should should able to send email using the following code

ps -aux | twilio email:send \
--from="" \
--to="" \
--subject="Current processes" \
--text="See attachment"'

Lets do an example of sending Nginx summary using sendGrid...

date +"%FORMAT"
heading="top 20 most requested broken links"
top_20_most_requested_broken_links=$(awk '($9 ~ /404/)' access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head -20|sed 's/$/<br>/g')

To make sure every result is printed on new line we need to append <br>

text=$(echo -e "$heading<br>$top_20_most_requested_broken_links<br><br>")
twilio email:send \
--from="from_email" \
--to="to_email1,to_email2" \
--subject="Nginx Summary $todaysdate" \

How to use SendGrid using Python

Install latest Python client using pip.

pip install sendgrid

If you see some syntax error such as the one below...

TypeError: __init__() got an unexpected keyword argument 'html_content'

Make sure you install the latest version. You can check the latest version here

pip install sendgrid==6.0.5

Once you have it installed, use the following code to send email...

  message = Mail(
    subject='Please confirm your email - From',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
    sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(message)
  except Exception as e:

Related Posts