Thursday, December 25, 2014

Testing sendmail with a HERE document


All too often I find myself having to test email from a server.  You can do this with a text file and sendmail, but often I prefer having something I can copy/paste into the terminal.

You can achieve this by using what's called a Here Document.  A Here document is a special-purpose code block that can feed a command list into a pipe or variable.

Here documents use a termination character (EOF below) to delimiter the beginning and end of the document.  Below the email message is redirected into the EMAIL_MESSAGE variable, then passed to sendmail via a pipe.

#!/bin/bash

read -r -d '' EMAIL_MESSAGE <<'EOF'
To: user@example.com
Subject: Test Subject
From: user2@example.com

This is a test message.
EOF

echo "$EMAIL_MESSAGE" | sendmail -v -t

You can pretty much use Here documents for any kind of in-place code you need.  Here's an example of some python code you can embed in a bash script to extract JSON:

read -r -d '' SAMPLE_PYTHON_SCRIPT <<'EOF'
import os
import json
import sys

json_data = open(sys.argv[1])
data = json.load(json_data)
print data["element"][1]

json_data.close()
EOF

python -c "$SAMPLE_PYTHON_SCRIPT" test.json

You can read more about here docs in the official bash scripting guide or this fantastic SO entry.


No comments:

Post a Comment