【问题标题】:Receive and Parse Emails on AWS SES在 AWS SES 上接收和解析电子邮件
【发布时间】:2019-01-19 13:37:06
【问题描述】:

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

【问题讨论】:

    标签: python aws-lambda amazon-ses


    【解决方案1】:

    您可以在 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
    

    【讨论】:

      【解决方案2】:

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

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

      其次,在 S3 操作 之后(在与您的 S3 操作相同的 SES receipt 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);
                  }
              });
      };
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 这似乎是在接收 SQS 消息(事件),而不是 SES(邮件消息)。我错过了什么?
        猜你喜欢
        • 1970-01-01
        • 2018-09-18
        • 2017-01-30
        • 2018-10-06
        • 2023-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多