首页 > 解决方案 > 电子邮件转发:Python AWS lambda 函数产生错误的 FROM 地址

问题描述

lambda 函数旨在使用 AWS 简单电子邮件服务 (SES) 进行电子邮件转发。“发件人”地址代表 AWS 托管的电子邮件收件箱,其中填满了消息。通过调用 lambda 函数对每个单独存储的电子邮件文件执行 S3 操作,这些消息被转发到最终的“收件人”地址。发件人和收件人电子邮件地址都在 SES 电子邮件验证系统中进行验证。但是,SES 正在阻止电子邮件转发。它检测到“发件人”地址等于“原始发件人”地址,根据定义,它代表一个未经验证的地址,因为它来自随机网站访问者。我的问题是,如何更改最终的消息结构以包含适当的“发件人”

import email
import os
import boto3
from botocore.exceptions import ClientError

region = os.environ['Region']


def get_message_from_s3(message_id):
    incoming_email_bucket = os.environ['MailS3Bucket']
    incoming_email_prefix = os.environ['MailS3Prefix']
    print("incoming_email_bucket " + incoming_email_bucket)
    print("incoming_email_prefix " + incoming_email_prefix)

    if incoming_email_prefix:
        object_path = (incoming_email_prefix + "/" + message_id)
    else:
        object_path = message_id

    object_http_path = (
        f"http://s3.console.aws.amazon.com/s3/object/{incoming_email_bucket}/{object_path}?region={region}")
    print("object_http_path " + object_http_path)

    # Create a new S3 client.
    client_s3 = boto3.client("s3")

    # Get the email object from the S3 bucket.
    object_s3 = client_s3.get_object(Bucket=incoming_email_bucket, Key=object_path)
    # Read the content of the message.
    file = object_s3['Body'].read()

    file_dict = {
        "file": file,
        "path": object_http_path
    }

    return file_dict


def create_message(file_dict):
    sender = os.environ['MailSender']
    print("sender " + sender)

    recipient = os.environ['MailRecipient']
    print("recipient " + recipient)

    # The email message is loaded from a file.
    email_message_original = email.message_from_string(file_dict['file'].decode('utf-8'))

    # Create a new subject line.
    subject_original = email_message_original['Subject']
    print("subject_original " + subject_original)

    separator = ";"
    print("The message was received from "
          + separator.join(email_message_original.get_all('From'))
          + ". This message is archived at " + file_dict['path'])

    email_message_original.replace_header("From", sender)
    email_message_original.replace_header("To", recipient)

    message = {
        "Source": sender,
        "Destinations": recipient,
        # copy data from the original email message.
        "Data": email_message_original.as_string()
    }

    return message


def send_email(message):
    # Create a new SES client.
    client_ses = boto3.client('ses', region)

    # Send the email.
    try:
        # Provide the contents of the email.
        response = client_ses.send_raw_email(
            Source=message['Source'],
            Destinations=[
                message['Destinations']
            ],
            RawMessage={
                'Data': message['Data']
            }
        )

    # Display an error if something goes wrong.
    except ClientError as e:
        output = e.response['Error']['Message']
    else:
        output = "Email sent! Message ID: " + response['MessageId']

    return output


def lambda_handler(event, context):
    # get the email message id
    message_id = event['Records'][0]['ses']['mail']['messageId']
    print(f"Received message ID {message_id}")

    # Retrieve the file from the S3 bucket.
    file_dict = get_message_from_s3(message_id)

    # Create the message.
    message = create_message(file_dict)

    # Send the email and print the result.
    result = send_email(message)
    print(result)

标签: pythonamazon-web-servicesemailaws-lambdaamazon-simple-email-service

解决方案


您将在“返回路径”下找到发件人地址

mailobject = email.message_from_string(file_dict['file'].decode('utf-8'))
sentFrom = mailobject['Return-Path']

推荐阅读