Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
AWS Lambda Function to send SMTP Email
import smtplib
import os
def send_email(host, port, username, password, subject, body, mail_to, mail_from = None, reply_to = None):
if mail_from is None: mail_from = username
if reply_to is None: reply_to = mail_to
message = """From: %s\nTo: %s\nReply-To: %s\nSubject: %s\n\n%s""" % (mail_from, mail_to, reply_to, subject, body)
print (message)
server = smtplib.SMTP(host, port)
server.login(username, password)
server.sendmail(mail_from, mail_to, message)
return True
except Exception as ex:
print (ex)
return False
def lambda_handler(event, context):
# initialize variables
username = os.environ['USERNAME']
password = os.environ['PASSWORD']
host = os.environ['SMTPHOST']
port = os.environ['SMTPPORT']
mail_from = os.environ.get('MAIL_FROM')
mail_to = os.environ['MAIL_TO'] # separate multiple recipient by comma. eg: ","
origin = os.environ.get('ORIGIN')
origin_req = event['headers'].get('Host')
reply_to = event['queryStringParameters'].get('reply')
subject = event['queryStringParameters']['subject']
body = event['body']
# vaildate cors access
cors = ''
if not origin:
cors = '*'
elif origin_req in [o.strip() for o in origin.split(',')]:
cors = origin_req
# send mail
success = False
if cors:
success = send_email(host, port, username, password, subject, body, mail_to, mail_from, reply_to)
# prepare response
response = {
"isBase64Encoded": False,
"headers": { "Access-Control-Allow-Origin": cors }
if success:
response["statusCode"] = 200
response["body"] = '{"status":true}'
elif not cors:
response["statusCode"] = 403
response["body"] = '{"status":false}'
response["statusCode"] = 400
response["body"] = '{"status":false}'
return response

rambabusaravanan commented Aug 5, 2017

Environment Variables

PASSWORD: { app-specific-password }
MAIL_FROM: Alias Name <> (Optional)
MAIL_TO: Recipient1 <>, Recipient2 <>
ORIGIN:, (Optional)

Query Params

subject="System Notice"
reply="" (Optional)

Request Body

[ Email Text Message ]

rambabusaravanan commented Aug 15, 2017

Replace the string 'Host' with 'origin' at line number 32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment