Odyssey
CreateCustomVerificationTemplate.py
1 #!/usr/bin/env python
2 
3 """ Create AWS SES custom verification email template
4 
5 This script is used to mimic the following aws ses custom verification
6 email template creation function:
7 
8 aws ses create-custom-verification-email-template
9  --template-name <template-name>
10  --from-email-address <from-email-address>
11  --template-subject <template-subject>
12  --template-content <template-content>
13  --success-redirection-url <success-redirection-url>
14  --failure-redirection-url <failure-redirection-url>
15 
16 
17 Default AWS_REGION is `us-west-2` but the tempalte can be created in other
18 regions by setting up AWS_REGION env variable (check aws docuementation
19 for restrictions in certain regions.)
20 
21 As os 2018-10-02, Update and Deletion of existing templates need to be
22 performed using the aws account with sufficient permissions to perform those
23 operations. If the local dev user is decided to grant such permissions in
24 the future, this script can be extended for deletion and update of the
25 existing custom verification email templates.
26 
27 As of 2018-10-02, you can only run 4
28 `create-custom-verification-email-template` aws ses requests in a day in each
29 region.
30 """
31 
32 import sys
33 import boto3
34 import os
35 import json
36 import argparse
37 from botocore.exceptions import ClientError
38 
39 # Use `us-west-2` as default region
40 # This should work for local development, alpha stack(us-east-2) and prod
41 AWS_REGION = os.getenv('AWS_REGION', 'us-west-2')
42 
43 
44 # Path to default verification email contents
45 VERIFICATION_TEMPLATE = os.getenv('DEFAULT_VERIFICATION_TEMPLATE_PATH',
46  ('/home/homecu/tmp/aws/ses/'
47  'default_verification_email_template'))
48 
49 USAGE = ("USAGE: CreateCustomVerificationTemplate.py [-h] -tn TEMPLATE_NAME "
50  "[-fe FROM_EMAIL_ADDRESS] [-su SUBJECT] [-c CONTENT]"
51  "[-s SUCCESS] [-f FAILURE]")
52 
53 
55  '''return custom email verification template defaults'''
56  contents = None
57  with open(VERIFICATION_TEMPLATE, 'r') as fh:
58  contents = ''.join(fh.readlines())
59 
60  return {
61  "sender": "support@homecu.com",
62  "subject": "Please confirm your email address",
63  "content": contents,
64  "success": ("https://my.homecu.net/admbin/static/html/"
65  "AdmEmailSuccess.html"),
66  "failure": ("https://my.homecu.net/admbin/static/html/"
67  "AdmEmailFailure.html"),
68  }
69 
70 
71 class CustomArgumentParser(argparse.ArgumentParser):
72  """Custom ArgumentParser class
73 
74  Extends:
75  argparse.ArgumentParser
76  """
77 
78  def error(self, message):
79  """Suppressing default error method
80 
81  Return custom error message on ArgumentParser.error.
82 
83  Arguments:
84  message -- error message
85 
86  Raises:
87  SystemExit
88  """
89  custom_error = {
90  'status': '999',
91  'error': USAGE,
92  'response': {}
93  }
94  print(json.dumps("{}: {}".format(__file__, custom_error)))
95  raise SystemExit(2)
96 
97 
98 def get_parser():
99  """Prepare argument parser.
100 
101  Returns:
102  parser -- ArgumentParser object
103  """
104  defaults = get_email_defaults()
105  parser = CustomArgumentParser(
106  description="AWS SES Create New Custom Email Verification Template."
107  )
108 
109  parser.add_argument("-tn", "--template-name",
110  help=('Name of the custom verification email template'
111  '(required)'),
112  required=True
113  )
114 
115  parser.add_argument("-fe", "--from-email-address",
116  help="Sender's email address (from email address)",
117  default=defaults["sender"]
118  )
119 
120  parser.add_argument("-su", "--subject",
121  help="Email subject",
122  default=defaults["subject"]
123  )
124 
125  parser.add_argument("-c", "--content",
126  help=('Email content (single lined json text with no '
127  'breaks)'),
128  default=defaults["content"]
129  )
130 
131  parser.add_argument("-s", "--success",
132  help="Success redirection url",
133  default=defaults["success"]
134  )
135 
136  parser.add_argument("-f", "--failure",
137  help="Failure redirection url",
138  default=defaults["failure"]
139  )
140  return parser
141 
142 
143 def main(argv):
144  """Main method to create custom verification template
145 
146  Arguments:
147  argv {list} -- list of script arguments
148 
149  Raises:
150  SystemExit -- [description]
151  """
152  main_return = {
153  'status': '000',
154  'error': '',
155  'response': {}
156  }
157 
158  # get argument parser
159  parser = get_parser()
160  try:
161  args = parser.parse_args(argv)
162  except (argparse.ArgumentError, Exception) as e:
163  main_return = {
164  'status': '999',
165  'error': e,
166  'response': {}
167  }
168  print(json.dumps(main_return))
169  raise SystemExit(2)
170 
171  response = None
172  excption = False
173  try:
174 
175  # Create boto3 client object
176  client = boto3.client('ses', region_name=AWS_REGION)
177 
178  # Create custom verification email template on a specified region
179  response = client.create_custom_verification_email_template(
180  TemplateName=args.template_name,
181  FromEmailAddress=args.from_email_address,
182  TemplateSubject=args.subject,
183  TemplateContent=args.content,
184  SuccessRedirectionURL=args.success,
185  FailureRedirectionURL=args.failure
186  )
187 
188  except ClientError as e:
189  main_return['status'] = '999'
190  main_return['error'] = e.response["Error"]["Message"]
191  excption = True
192  except BaseException as e:
193  main_return['status'] = '999'
194  main_return['error'] = str(e)
195  excption = True
196  except Exception as e:
197  main_return['status'] = '999'
198  main_return['error'] = e
199  excption = True
200 
201  main_return["response"] = response
202  print(json.dumps(main_return))
203 
204  if excption:
205  raise SystemExit(2)
206 
207 
208 def run():
209  """Script entrypoint"""
210  main(sys.argv[1:])
211 
212 
213 if __name__ == "__main__":
214  run()