Last active
November 7, 2023 03:35
-
-
Save rambabusaravanan/dfa2b80369c89ce7517855f4094367e6 to your computer and use it in GitHub Desktop.
AWS Lambda Function to send SMTP Email
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
try: | |
server = smtplib.SMTP(host, port) | |
server.ehlo() | |
server.starttls() | |
server.login(username, password) | |
server.sendmail(mail_from, mail_to, message) | |
server.close() | |
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: "[email protected], [email protected]" | |
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}' | |
else: | |
response["statusCode"] = 400 | |
response["body"] = '{"status":false}' | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wasn’t able to send email using Gmail username/password. I made following changes to make it work.
Create password for external App(In our case
Lambda function
)Got to Google Account Security and Scroll down to "Signing in to Google" option. If you don't have 2 step verification on; enable it. Then you will see "App passwords" option. Generate a password for your lambda function.
Sample lambda function in python to check SMTP server
I have used a this following code to verify my SMTP server is working.
Send attachment using SMTP server
As I have used xlsWriter module to create Excel file, I had to create a lambda layer for that. First I will explain how I created the lambda layer.
xlsWriterlambda layer creation:
Create a file
xlsWriter.py
on your local~/Desktop
path and copy/paste the following command. It will createxlswriter.zip
file on your Desktop.After creating the zip file use following steps to upload file and create the layer.
xlswriter.zip
file.There are some other fields such as Description, Compatible architectures, Compatible runtimes, etc. These are optionals.
Sample lambda function in python to send an attachment:
SMTP_attachment_lambda
./tmp
folder. Else you will get following error"errorMessage": "[Errno 30] Read-only file system: '/hello.xlsx'"
__init.py__
file. Else you will get lots of following error"File \"<frozen importlib._bootstrap>\"