Skip to content

Instantly share code, notes, and snippets.

@sangwonl
Last active December 28, 2017 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sangwonl/67124242649e57ec80286f69f56f5918 to your computer and use it in GitHub Desktop.
Save sangwonl/67124242649e57ec80286f69f56f5918 to your computer and use it in GitHub Desktop.
# This code snippet is based on python 3.
from datetime import datetime
from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.error import HTTPError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os
import hmac
import base64
import hashlib
# prepare for raw message data
SENDER = 'Sangwon Lee <gamzabaw@gmail.com>'
RECIPIENT = 'youyou@testmail.xxx'
SUBJECT = 'Email Title Here'
ATTACHMENT = '/tmp/some/attachment.txt'
BODY_TEXT = 'TXT body here...'
CHARSET = 'utf-8'
msg = MIMEMultipart('mixed')
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = RECIPIENT
textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
msg_body = MIMEMultipart('alternative')
msg_body.attach(textpart)
msg.attach(msg_body)
att = MIMEApplication(open(ATTACHMENT, 'rb').read())
att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT))
msg.attach(att)
raw_msg_bytes = base64.b64encode(msg.as_string().encode()).decode()
# make a signature of secret key
awsId = '<your-aws-access-id>'
awsSecret = '<your-aws-access-secrey-key>'
dateValue = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
h = hmac.new(key=awsSecret.encode(), msg=dateValue.encode(), digestmod=hashlib.sha256)
signature = base64.b64encode(h.digest()).decode()
# compose http request header
headers = {
'X-Amzn-Authorization': 'AWS3-HTTPS AWSAccessKeyId={}, Algorithm=HMACSHA256, Signature={}'.format(awsId, signature),
'Content-type': 'application/x-www-form-urlencoded',
'Return-Path': 'gamzabaw@gmail.com',
'Date': dateValue,
}
# compose parameters for urlencoded form data
params = {
'Action': 'SendRawEmail',
'RawMessage.Data': raw_msg_bytes,
}
# send request
AWS_REGION = 'us-east-1'
url = 'https://email.{}.amazonaws.com'.format(AWS_REGION)
req = Request(url, data=urlencode(params).encode(), headers=headers)
try:
res = urlopen(req).read()
except HTTPError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment