How to Apply API Gateway for DirectMail in Python

Calculating the correct dates

# Correctly formatted date and time
now = datetime.datetime.utcnow()
# Date used by the HTTP "Date" header
date = now.strftime("%a, %d %b %Y %H:%M:%S GMT")
# Date used by the API parameter "Timestamp"
utc = now.isoformat(timespec='seconds') + 'Z'

Complete Program to Call DirectMail REST API and Send an Email

############################################################
# Version 1.00
# Date Created: 2018-05-26
# Last Update: 2018-05-27
# https://www.neoprime.io
# Copyright (c) 2018, NeoPrime, LLC
############################################################
""" Alibaba Cloud DirectMail REST API With Signing """import base64
import datetime
import hmac
import hashlib
import urllib
import uuid
import json
import requests
# My library for processing Alibaba Cloud Services (ACS) credentials
import mycred_acs
# From the DirectMail Console
dm_account = "<enter your value here>"
dm_alias = "<enter your value here>"
debug = 0def set_connection_logging():
""" Enable HTTP connection logging """
if debug is 0:
return
import logging
import http.client as http_client
http_client.HTTPConnection.debuglevel = 1 # You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
return
def get_uuid():
""" return a uuid as a signing nonce """
return str(uuid.uuid4())
def percentEncode(path):
""" Encode a URL """
res = urllib.parse.quote(path)
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
def my_urlencode(query):
""" Encode a Query """
res = urllib.parse.urlencode(query)
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
def build_request_string(table):
""" Build canonical list """
items = sorted(iter(table.items()), key=lambda d: d[0])
enc = my_urlencode(items)
return enc
def sign(string, secret):
""" Sign REST API Request """
nsecret = secret + '&'
h = hmac.new(
bytes(nsecret, "utf-8"),
bytes(string, "utf-8"),
hashlib.sha1)
#sig = base64.b64encode(h.digest())
sig = str(base64.encodebytes(h.digest()).strip(), "utf-8")
return sig
def sendEmail(credentials, subject, body, body_text, to_list):
""" Send an email using Alibaba DirectMail """
# HTTP Method
method = "POST"
# Correctly formatted date and time
now = datetime.datetime.utcnow()
date = now.strftime("%a, %d %b %Y %H:%M:%S GMT")
utc = now.isoformat(timespec='seconds') + 'Z'
# HTTP Host header
host = "dm.ap-southeast-1.aliyuncs.com"
# URL for POST
url = "https://dm.ap-southeast-1.aliyuncs.com/"
parameters = {} # Add the DirectMail public request parameters
parameters["Format"] = "json"
parameters["AccessKeyId"] = credentials['AccessKey']
parameters["SignatureMethod"] = "HMAC-SHA1"
parameters["SignatureType"] = ""
parameters["SignatureVersion"] = "1.0"
parameters["SignatureNonce"] = get_uuid()
parameters["Timestamp"] = utc
#parameters["Version"] = "2015-11-23"
parameters["Version"] = "2017-06-22"
parameters["RegionId"] = "ap-southeast-1"
# Add parameters that are always set
parameters["Action"] = "SingleSendMail"
parameters["AddressType"] = "1"
parameters["ReplyToAddress"] = "true"
# Add the DirectMail API parameters
parameters["AccountName"] = dm_account
parameters["FromAlias"] = dm_alias
parameters["ToAddress"] = to_list
parameters["Subject"] = subject
parameters["HtmlBody"] = body
parameters["textBody"] = body_text
# Build the request string for the signing process
params = build_request_string(parameters)
# Create the actual string to sign
stringToSign = method + "&%2F&" + percentEncode(params)
#print("String to Sign")
#print(stringToSign)
Signature = sign(stringToSign, credentials['AccessKeySecret'])
#print("Signature", Signature)
parameters["Signature"] = Signature headers = {
'Date': date,
'Host': host
}
set_connection_logging() print("Sending Email to", parameters["ToAddress"])
r = requests.post(url, data=parameters, headers=headers)
if r.status_code != 200:
print("Error: Email Send Failed:", r.status_code)
print(r.text)
return 1
#print(r.text) result = json.loads(r.text)
print("Success: Request ID:", result['RequestId'])
return 0# Load the Alibaba Cloud Credentials (AccessKey)
cred = mycred_acs.LoadCredentials()
dm_subject = "Welcome to Alibaba Cloud DirectMail"dm_body = "<h2>Welcome to Alibaba Cloud DirectMail<h2>You are receiving this email as part of a test program.<br /><br />Click for <a href='https://www.neoprime.io/info/alibaba/'>more information<a>.<br /><br /><a href='https://www.alibabacloud.com/'><img src='https://www.neoprime.io/info/alibaba/img/alibaba-600x263.png' alt='Alibaba' width='700'><a>"dm_body_text = "Welcome to Alibaba Cloud DirectMail\nYou are receiving this email as part of a test program."dm_to_list = "test@test.com, test2@test.comsendEmail(cred, dm_subject, dm_body, dm_body_text, dm_to_list)

Related Blog Posts

Alibaba Cloud DevOps Cookbook Part 1 — CLI, SDK, SSH, SFTP

Alibaba Cloud DevOps Cookbook Part 3 — Function Compute with Python 3.0

Related Market Product

Spark Mllib Hadoop Core powered by Miri Infotech

Related Documentation

SMTP — Python

Set HTTPS requests

Related Products

Direct Mail

Elastic Compute Service

Related Course

A Quick Guide to Process Structured Data with Python

--

--

--

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Several server statuses and their meanings

Cr0wn_Gh0ul’s Point puzzle write-up

Is it hard to compare Software Development teams’ productivity?

Simple Isn’t Easy — In Programming

Test automation essentials for a good start

Service Mesh Architecture in Action

The C Programming Language

Setup developer environment on new MacBook

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com

More from Medium

TIL : Using python decorators to secure method invocation.

Transforming nested json with pyjq: recommended for a deep night sleep

GitHub Actions: The Good, the Bad, and the Ugly

Click-params: a little companion to your click project

An image showing a terminal loading a software