在AWS SE上接收和解析电子邮件

2024-10-01 13:43:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想设置一个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()

Tags: 文档txt脚本信息parser电子邮件splitses
3条回答

您可以在SES规则集中设置一个操作来自动将电子邮件文件放入S3。然后在S3中设置一个事件(针对特定的bucket)来触发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

看来joarleymaraes建议了您正在寻找的多部分解决方案。我将进一步详细说明这个过程。首先,您需要在简单的电子邮件服务中使用S3 Action。在

  1. SES S3 Action-将您的电子邮件放入S3存储桶

其次,在S3操作之后(在与S3操作相同的SESreceipt rule内)安排S3电子邮件处理Lambda Action触发器。在

  1. Lambda Action-从S3获取并处理电子邮件内容

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);
            }
        });
};

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()

相关问题 更多 >