Last active
January 18, 2024 23:34
-
-
Save jcttrll/52ff9b9f51588eeb18a3f09fe867e3ed to your computer and use it in GitHub Desktop.
Send an e-mail from the command line using AWS SES SMTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
set -o pipefail | |
# PREREQUISITES: | |
# | |
# 1. mailx command line utility | |
# 2. Firewall access to TLS SMTP port 465 on the SES server specified in SES_ENDPOINT, below. | |
# | |
# INSTRUCTIONS: | |
# | |
# 1. Create IAM user with ses:SendRawEmail permission; example policy: | |
# | |
# { | |
# "Version": "2012-10-17", | |
# "Statement": [{ | |
# "Action": "ses:SendRawEmail", | |
# "Resource": "*", | |
# "Effect": "Allow" | |
# }] | |
# } | |
# | |
# 2. Set ACCESS_KEY_ID and SECRET_ACCESS_KEY, below, for the access key of the IAM user. | |
# 3. Set FROM_ADDRESS, below, to an address authorized to send from SES. | |
# 4. Set TO_ADDRESS, below. Note: If your SES is still sandboxed, this address first will need to be verified in SES. | |
# 5. Edit SUBJECT, below, as desired. | |
# 6. Change SES_ENDPOINT to the endpoint for your region: http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-connect.html | |
ACCESS_KEY_ID= | |
SECRET_ACCESS_KEY= | |
FROM_ADDRESS= | |
TO_ADDRESS= | |
SUBJECT=Test | |
SES_ENDPOINT=email-smtp.us-west-2.amazonaws.com | |
hmac() { | |
local hexKey="$1" | |
local toSign="$2" | |
echo -n "$toSign" | openssl sha256 -binary -mac HMAC -macopt "hexkey:$hexKey" | od -t x1 -A n -w32 | sed 's/ //g' | |
} | |
toHex() { | |
local value="$1" | |
echo -n "$value" | od -t x1 -A n -w${#value} | sed 's/ //g' | |
} | |
hexToBase64() { | |
local hexValue="$1" | |
echo -n "$hexValue" | while read -r -n 2 byte; do printf "\\x$byte"; done | base64 | |
} | |
SECRET_ACCESS_KEY_HEX=$(toHex $SECRET_ACCESS_KEY) | |
MESSAGE=SendRawEmail | |
VERSION_HEX=02 | |
SIGNATURE_HEX=$VERSION_HEX$(hmac $SECRET_ACCESS_KEY_HEX $MESSAGE) | |
PASSWORD=$(hexToBase64 $SIGNATURE_HEX) | |
mailx \ | |
-r "$FROM_ADDRESS" \ | |
-s "$SUBJECT" \ | |
-S "smtp=smtps://$SES_ENDPOINT:465" \ | |
-S "smtp-auth-user=$ACCESS_KEY_ID" \ | |
-S "smtp-auth-password=$PASSWORD" \ | |
"$TO_ADDRESS" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment