Receive Email in AWS SES and Save in DynamoDB
Today, my customer came up with a requirment, where they want to do filtering and processing in customer emails.
So, Let see how to acheive this we need to do the following this:
1: verify your domain in SES.
Note: You have to select North Virginia region for this activity.
2: add MX record in your domain.
3: then we have to create a rule set and attached the lambda, SNS, S3 etc in action.
4: finally, when you receive any email on that Recipient, you action lambda/SNS will perform.
5: Now lambda code which will get your message from AWS SNS:
Below lambda will read the message and store the data in dynamodb:
1import json
2import boto3
3import random
4from botocore.exceptions import ClientError
5from boto3.dynamodb.conditions import Key, Attr
6import datetime
7import base64
8import quopri
9
10dynamodb = boto3.resource('dynamodb')
11client = boto3.client('dynamodb')
12Lambdaclient = boto3.client('lambda')
13
14def lambda_handler(event, context):
15 # TODO implement
16 sns_message = event['Records'][0]['Sns']['Message']
17 original_message = json.loads(sns_message)
18 From_id = original_message['mail']['source']
19 Encode_Message = original_message['content']
20 parsed_message = base64.b64decode(Encode_Message)
21 #parsed_message = ''.join(parsed_message.split("b", 1))
22 print("Form Email ID : "+ From_id)
23 #print("encode message: "+ Encode_Message)
24 #print("decode messgae : ", parsed_message)
25 if From_id == "<email-id>":
26 #print(parsed_message)
27 parsed_message = quopri.decodestring(parsed_message)
28 parsed_message = parsed_message.decode('latin-1', errors='ignore')
29 parsed_message = parsed_message.encode('utf-8')
30 parsed_message = parsed_message.decode("utf-8")
31 #print("New messgae : ", parsed_message)
32 content_message = parsed_message.split('Content-Transfer-Encoding: quoted-printable', 1)[-1]
33 html_message = content_message.split("\n--000000000", 1)[0]
34 table = dynamodb.Table('<table-name>')
35 responseID = table.scan()
36 id_number = 0
37 for i in responseID['Items']:
38 print(i['id'])
39 id_number = id_number + 1
40
41 date = datetime.datetime.now().strftime("%d-%m-%Y")
42 try:
43 id_number = id_number + 1
44 #print("id : ",id_number)
45 print("message :",html_message)
46 table.put_item(Item={
47 'id': id_number,
48 'Jobs': html_message,
49 'Date': date
50 }
51 )
52 except ClientError as e:
53 print(e.response['Error']['Message'])
Important: Change sender email-id to protect unwanted read and dynamodb table name to put message in dynamodb.
Note: To know how to add lambda in SNS, Please follow the this link