Guest User

Untitled

a guest
Nov 18th, 2017
1,652
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import smtplib
  2. import os
  3.  
  4. def send_email(host, port, username, password, subject, body, mail_to, mail_from = None, reply_to = None):
  5. if mail_from is None: mail_from = username
  6. if reply_to is None: reply_to = mail_to
  7.  
  8. message = """From: %s\nTo: %s\nReply-To: %s\nSubject: %s\n\n%s""" % (mail_from, mail_to, reply_to, subject, body)
  9. print (message)
  10. try:
  11. server = smtplib.SMTP(host, port)
  12. server.ehlo()
  13. server.starttls()
  14. server.login(username, password)
  15. server.sendmail(mail_from, mail_to, message)
  16. server.close()
  17. return True
  18. except Exception as ex:
  19. print (ex)
  20. return False
  21.  
  22. def lambda_handler(event, context):
  23.  
  24. # initialize variables
  25. username = os.environ['USERNAME']
  26. password = os.environ['PASSWORD']
  27. host = os.environ['SMTPHOST']
  28. port = os.environ['SMTPPORT']
  29. mail_from = os.environ.get('MAIL_FROM')
  30. mail_to = os.environ['MAIL_TO'] # separate multiple recipient by comma. eg: "abc@gmail.com, xyz@gmail.com"
  31. origin = os.environ.get('ORIGIN')
  32. origin_req = event['headers'].get('Host')
  33.  
  34. reply_to = event['queryStringParameters'].get('reply')
  35. subject = event['queryStringParameters']['subject']
  36. body = event['body']
  37.  
  38. # vaildate cors access
  39. cors = ''
  40. if not origin:
  41. cors = '*'
  42. elif origin_req in [o.strip() for o in origin.split(',')]:
  43. cors = origin_req
  44.  
  45. # send mail
  46. success = False
  47. if cors:
  48. success = send_email(host, port, username, password, subject, body, mail_to, mail_from, reply_to)
  49.  
  50. # prepare response
  51. response = {
  52. "isBase64Encoded": False,
  53. "headers": { "Access-Control-Allow-Origin": cors }
  54. }
  55. if success:
  56. response["statusCode"] = 200
  57. response["body"] = '{"status":true}'
  58. elif not cors:
  59. response["statusCode"] = 403
  60. response["body"] = '{"status":false}'
  61. else:
  62. response["statusCode"] = 400
  63. response["body"] = '{"status":false}'
  64. return response
Add Comment
Please, Sign In to add comment