How to mail the output of a command/script through sendgrid in linux

How to mail the output of a command/script through sendgrid in linux

Sometimes we want to have the output of a command emailed to us but without having to install and maintain an email server which can be time consuming and overkill for only few emails a day or month. Sendgrid is an excellent email sending platform and here’s a quick how-to and script using which you can send output of a command to your email.

Requirement:

  • Python (tested on 2.7.5)
  • PIP

First, let’s install the sendgrid module for python.

pip install sendgrid

Now, create a file named mail.py and put the following content:

import sys
import sendgrid
import os
from sendgrid.helpers.mail import *
stdin = sys.stdin.read()

stdin = stdin.replace("\n","<br>")

sg = sendgrid.SendGridAPIClient(apikey="API_KEY")
from_email = Email("FROM_EMAIL")
to_email = Email("YOUR_EMAIL")
subject = "Process completed for xyz"
content = Content("text/html","Some intro line <br><br>" + stdin)
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())

You can also use environment (.env) file to store API KEY

Suppose you have this file at /root, to use it, simply do this

echo "Hello world" | python /root/mail.py
Share:

Leave a Reply

Your email address will not be published. Required fields are marked *