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="me@example.com" \
--to="me@example.com" \
--subject="Current processes" \
--text="See attachment"'

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

date
date +"%FORMAT"
todaysdate=$(date)
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" \
--text="$text"

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 github.com/sendgrid/sendgrid-python/releases

pip install sendgrid==6.0.5

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

  message = Mail(
    from_email='%s'%from_email,
    to_emails='%s'%to_email,
    subject='Please confirm your email - From example.com',
    html_content='<strong>and easy to do anywhere, even with Python</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(str(e))


Related Posts