我想设置一个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()
答案 0 :(得分:4)
您可以在SES规则集中设置一个操作,以自动将您的电子邮件文件输入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
答案 1 :(得分:0)
请参阅Amazon Simple Email Service document
实际上,还有更好的方法;使用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()
答案 2 :(得分:0)
似乎joarleymoraes提出了您正在寻找的多部分解决方案。我将尝试进一步详细说明这一过程。首先,您需要在简单电子邮件服务中使用S3 Action。
第二,在 S3 Action 之后(与S3 Action在同一SES receipt rule 中)安排您的S3电子邮件处理Lambda Action触发器。
AWS SES documentation显示“ 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);
}
});
};