0

我創建了一個lambda函數,當文件上傳到s3存儲桶時發送電子郵件,但是現在我想要將與該文件相關的所有信息作爲名稱,大小,日期和上傳時間,以及它可能來自何處。 我在aws控制檯上擁有所有這些infortmation,但希望將它放在電子郵件正文中。獲取關於上傳到S3的文件的信息

我正在使用無服務器框架。 v 1.22.0

這裏是我的代碼

import json 
import boto3 
import botocore 
import logging 
import sys 
import os 
import traceback 


from botocore.exceptions import ClientError 
from pprint import pprint 
from time import strftime, gmtime 

email_from = '********@*****.com' 
email_to = '********@*****.com' 
email_subject = 'new event on s3 ' 
email_body = 'a new file is uploaded' 


#setup simple logging for INFO 
logger = logging.getLogger() 
logger.setLevel(logging.INFO) 

from botocore.exceptions import ClientError 

def sthree(event, context): 
"""Send email whenever a file is uploaded to S3""" 
body = {} 
status_code = 200 
email_body = str(context) 

try: 
    s3 = boto3.client('s3') 
    ses = boto3.client('ses') 
    ses.send_email(Source = email_from, 
       Destination = {'ToAddresses': [email_to,],}, 
        Message = {'Subject': {'Data': email_subject}, 'Body':{'Text' : {'Data': email_body}}} 
     ) 
except Exception as e: 
    print(traceback.format_exc()) 
    status_code = 500 
    body["message"] = json.dumps(e) 

response = { 
    "statusCode": 200, 
    "body": json.dumps(body) 
} 

return response 

回答

4

下面是在對象創建時由S3發送事件JSON結構: http://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html

您可以獲取文件名,大小和源IP像這樣:

for record in event['Records']: 
    filename = record['s3']['object']['key']; 
    filesize = record['s3']['object']['size']; 
    source = record['requestParameters']['sourceIPAddress']; 
    eventTime = record['eventTime']; 
+0

非常感謝你,這是非常有幫助 – ner

3
def lambda_handler(event, context): 
    s3 = boto3.client('s3') 
    email_from = '[email protected]' 
    email_to = '[email protected]' 
    email_subject = 'new event on s3' 
    email_body = "File Name :" + event[u'Records'][0][u's3'][u'object'][u'key'] + "\n" + "File Size :" + str(event[u'Records'][0][u's3'][u'object'][u'size']) + "\n" + "Upload Time :" + event[u'Records'][0][u'eventTime'] + "\n" + "User Details :" + event[u'Records'][0][u'userIdentity'][u'principalId'] 
    ses = boto3.client('ses') 
    ses.send_email(Source = email_from, 
       Destination = {'ToAddresses': [email_to,],}, 
        Message = {'Subject': {'Data': email_subject}, 'Body':{'Text' : {'Data': email_body}}} 
     ) 
    print("Function execution Completed !!!") 

˚F從這post

+0

非常感謝你的兄弟,解決我的問題 – ner