我想设置一个Lambda函数来将传入的电子邮件解析为SES。我遵循文件并设置了收据规则。
我测试了我的脚本,将MIME电子邮件存储在一个txt文件中,解析电子邮件,并将所需的信息存储在一个JSON文档中,然后存储在数据库中。现在,我不确定如何访问从SES收到的电子邮件并将信息拉入我的Python脚本中。任何帮助都将非常感激。
from email.parser import Parser
parser = Parser()
f = open('roundtripMime.txt', "r")
rawText = f.read()
incoming = Parser().parsestr(rawText)
subject = incoming
subjectList = subject.split("|")
#Get number
NumberList = subjectList[0].split()
Number = NumberList[2].strip("()")
#Get Name
fullNameList = subjectList[3].split("/")
firstName = fullNameList[1].strip()
lastName = fullNameList[0].strip()
您可以在您的SES Rules set中设置一个Action来自动将您的电子邮件文件放入S3。然后在S3中设置一个事件(针对特定桶)来触发lambda函数。有了它,您将能够像这样检索电子邮件:
def lambda_handler(event, context):
for record in event['Records']:
key = record['s3']['object']['key']
bucket = record['s3']['bucket']['name']
# here you can download the file from s3 with bucket and key
joarleymoraes似乎建议了您正在寻找的多部分解决方案。我会试着进一步阐述这个过程。首先,您需要在Simple Email Service中使用S3 Action。
- SES S3 Action - 将您的电子邮件放入S3 bucket
第二,在S3 Action之后(在与S3 Action相同的SES 接收规则中)安排S3电子邮件处理Lambda Action触发器。
- Lambda Action - 从S3获取并处理邮件内容
AWS SES文档显示了"Lambda函数示例#4",演示了从S3获取电子邮件所需的步骤:
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var bucketName = '<YOUR BUCKET GOES HERE>';
exports.handler = function(event, context, callback) {
console.log('Process email');
var sesNotification = event.Records[0].ses;
console.log("SES Notification:n", JSON.stringify(sesNotification, null, 2));
// Retrieve the email from your bucket
s3.getObject({
Bucket: bucketName,
Key: sesNotification.mail.messageId
}, function(err, data) {
if (err) {
console.log(err, err.stack);
callback(err);
} else {
console.log("Raw email:n" + data.Body);
// Custom email processing goes here
callback(null, null);
}
});
};
参见Amazon Simple Email Service文档
事实上,有更好的方法;使用boto3,您可以轻松地发送电子邮件和处理消息。
# Get the service resource
sqs = boto3.resource('sqs')
# Get the queue
queue = sqs.get_queue_by_name(QueueName='test')
# Process messages by printing out body and optional author name
for message in queue.receive_messages(MessageAttributeNames=['Author']):
# Get the custom author message attribute if it was set
author_text = ''
if message.message_attributes is not None:
author_name = message.message_attributes.get('Author').get('StringValue')
if author_name:
author_text = ' ({0})'.format(author_name)
# Print out the body and author (if set)
print('Hello, {0}!{1}'.format(message.body, author_text))
# Let the queue know that the message is processed
message.delete()