Instantly share code, notes, and snippets.

Embed
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)
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: "abc@gmail.com, xyz@gmail.com"
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
@rambabusaravanan

This comment has been minimized.

Show comment
Hide comment
@rambabusaravanan

rambabusaravanan Aug 5, 2017

Environment Variables

SMTPHOST: smtp.gmail.com
SMTPPORT: 587
USERNAME: yourname@domain.com
PASSWORD: { app-specific-password }
MAIL_FROM: Alias Name <alias@domain.com> (Optional)
MAIL_TO: Recipient1 <recipient1@domain.com>, Recipient2 <recipient2@domain.com>
ORIGIN: https://domain.com, https://www.domain.com (Optional)

Query Params

subject="System Notice"
reply="reply@domain.com" (Optional)

Request Body

[ Email Text Message ]
Owner

rambabusaravanan commented Aug 5, 2017

Environment Variables

SMTPHOST: smtp.gmail.com
SMTPPORT: 587
USERNAME: yourname@domain.com
PASSWORD: { app-specific-password }
MAIL_FROM: Alias Name <alias@domain.com> (Optional)
MAIL_TO: Recipient1 <recipient1@domain.com>, Recipient2 <recipient2@domain.com>
ORIGIN: https://domain.com, https://www.domain.com (Optional)

Query Params

subject="System Notice"
reply="reply@domain.com" (Optional)

Request Body

[ Email Text Message ]
@rambabusaravanan

This comment has been minimized.

Show comment
Hide comment
@rambabusaravanan

rambabusaravanan Aug 15, 2017

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

Owner

rambabusaravanan commented Aug 15, 2017

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

@ashishhavells

This comment has been minimized.

Show comment
Hide comment
@ashishhavells

ashishhavells Apr 16, 2018

Hi you may use below codes for creating multiple backups in a day with instance name:

import boto3
import collections
import datetime
import sys
import pprint

ec = boto3.client('ec2')
#image = ec.Image('id')

def lambda_handler(event, context):

reservations = ec.describe_instances(
    Filters=[
        {'Name': 'tag-key', 'Values': ['odd', 'Odd']},
    ]
).get(
    'Reservations', []
)
print "Hello",
for h in reservations:
    print h
instances = sum(
    [
        [i for i in r['Instances']]
        for r in reservations
    ], [])

print "Found %d instances that need backing up" % len(instances)

to_tag = collections.defaultdict(list)

for instance in instances:
    try:
        retention_days = [
            int(t.get('Value')) for t in instance['Tags']
            if t['Key'] == 'Retention'][0]
    except IndexError:
        retention_days = 7
        
    finally:

    #for dev in instance['BlockDeviceMappings']:
    #    if dev.get('Ebs', None) is None:
    #        continue
    #    vol_id = dev['Ebs']['VolumeId']
    #    print "Found EBS volume %s on instance %s" % (
    #        vol_id, instance['InstanceId'])

        #snap = ec.create_snapshot(
        #    VolumeId=vol_id,
        #)
        
        #create_image(instance_id, name, description=None, no_reboot=False, block_device_mapping=None, dry_run=False)
        # DryRun, InstanceId, Name, Description, NoReboot, BlockDeviceMappings
        create_time = datetime.datetime.now()
        create_fmt = create_time.strftime('%H-%M-%S--%Y-%m-%d')
    
        #Variables for storing ec2 Instance Name and ec2 Instance ID
        ec2_Instance_Name = ''
        ec2_Instance_ID = ''
        ec2_Instance_ID = instance['InstanceId']
        ec2_Instance_Name = get_instance_name(ec2_Instance_ID)
        
        AMIid = ec.create_image(InstanceId=instance['InstanceId'], Name="Lambda - " + instance['InstanceId'] + " " + ec2_Instance_Name + " (Odd) from " + create_fmt, Description="Lambda created AMI of instance " + instance['InstanceId'] + " from " + create_fmt, NoReboot=True, DryRun=False)

    
        pprint.pprint(instance)
        #sys.exit()
        #break
    
        #to_tag[retention_days].append(AMIid)
        
        to_tag[retention_days].append(AMIid['ImageId'])
        
        print "Retaining AMI %s of instance %s for %d days" % (
            AMIid['ImageId'],
            instance['InstanceId'],
            retention_days,
        )

print to_tag.keys()

for retention_days in to_tag.keys():
    delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
    delete_fmt = delete_date.strftime('%m-%d-%Y')
    print "Will delete %d AMIs on %s" % (len(to_tag[retention_days]), delete_fmt)
    
    #break

    ec.create_tags(
        Resources=to_tag[retention_days],
        Tags=[
            {'Key': 'DeleteOn', 'Value': delete_fmt},
        ]
    )

Function to get Instance Name

def get_instance_name(fid):
# When given an instance ID as str e.g. 'i-1234567', return the instance 'Name' from the name tag.
ec2 = boto3.resource('ec2')
ec2instance = ec2.Instance(fid)
instancename = ''
for tags in ec2instance.tags:
if tags["Key"] == 'Name':
instancename = tags["Value"]
return instancename

ashishhavells commented Apr 16, 2018

Hi you may use below codes for creating multiple backups in a day with instance name:

import boto3
import collections
import datetime
import sys
import pprint

ec = boto3.client('ec2')
#image = ec.Image('id')

def lambda_handler(event, context):

reservations = ec.describe_instances(
    Filters=[
        {'Name': 'tag-key', 'Values': ['odd', 'Odd']},
    ]
).get(
    'Reservations', []
)
print "Hello",
for h in reservations:
    print h
instances = sum(
    [
        [i for i in r['Instances']]
        for r in reservations
    ], [])

print "Found %d instances that need backing up" % len(instances)

to_tag = collections.defaultdict(list)

for instance in instances:
    try:
        retention_days = [
            int(t.get('Value')) for t in instance['Tags']
            if t['Key'] == 'Retention'][0]
    except IndexError:
        retention_days = 7
        
    finally:

    #for dev in instance['BlockDeviceMappings']:
    #    if dev.get('Ebs', None) is None:
    #        continue
    #    vol_id = dev['Ebs']['VolumeId']
    #    print "Found EBS volume %s on instance %s" % (
    #        vol_id, instance['InstanceId'])

        #snap = ec.create_snapshot(
        #    VolumeId=vol_id,
        #)
        
        #create_image(instance_id, name, description=None, no_reboot=False, block_device_mapping=None, dry_run=False)
        # DryRun, InstanceId, Name, Description, NoReboot, BlockDeviceMappings
        create_time = datetime.datetime.now()
        create_fmt = create_time.strftime('%H-%M-%S--%Y-%m-%d')
    
        #Variables for storing ec2 Instance Name and ec2 Instance ID
        ec2_Instance_Name = ''
        ec2_Instance_ID = ''
        ec2_Instance_ID = instance['InstanceId']
        ec2_Instance_Name = get_instance_name(ec2_Instance_ID)
        
        AMIid = ec.create_image(InstanceId=instance['InstanceId'], Name="Lambda - " + instance['InstanceId'] + " " + ec2_Instance_Name + " (Odd) from " + create_fmt, Description="Lambda created AMI of instance " + instance['InstanceId'] + " from " + create_fmt, NoReboot=True, DryRun=False)

    
        pprint.pprint(instance)
        #sys.exit()
        #break
    
        #to_tag[retention_days].append(AMIid)
        
        to_tag[retention_days].append(AMIid['ImageId'])
        
        print "Retaining AMI %s of instance %s for %d days" % (
            AMIid['ImageId'],
            instance['InstanceId'],
            retention_days,
        )

print to_tag.keys()

for retention_days in to_tag.keys():
    delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
    delete_fmt = delete_date.strftime('%m-%d-%Y')
    print "Will delete %d AMIs on %s" % (len(to_tag[retention_days]), delete_fmt)
    
    #break

    ec.create_tags(
        Resources=to_tag[retention_days],
        Tags=[
            {'Key': 'DeleteOn', 'Value': delete_fmt},
        ]
    )

Function to get Instance Name

def get_instance_name(fid):
# When given an instance ID as str e.g. 'i-1234567', return the instance 'Name' from the name tag.
ec2 = boto3.resource('ec2')
ec2instance = ec2.Instance(fid)
instancename = ''
for tags in ec2instance.tags:
if tags["Key"] == 'Name':
instancename = tags["Value"]
return instancename

@ashishhavells

This comment has been minimized.

Show comment
Hide comment
@ashishhavells

ashishhavells Apr 16, 2018

can anyone help me to generate summary in mail for daily backup detail.
Like:
AMI Name and Backup Status.

ashishhavells commented Apr 16, 2018

can anyone help me to generate summary in mail for daily backup detail.
Like:
AMI Name and Backup Status.

@rambabusaravanan

This comment has been minimized.

Show comment
Hide comment
@rambabusaravanan

rambabusaravanan Aug 22, 2018

Good one to note 🎉 👍

Owner

rambabusaravanan commented Aug 22, 2018

Good one to note 🎉 👍

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