AWS SES使用Python将电子邮件发送到多个收件人

时间:2019-06-24 05:30:18

标签: amazon-web-services aws-lambda amazon-ses

我是AWS Lambda函数的新手。

我想向多个收件人发送电子邮件。我能够将电子邮件发送到单个电子邮件地址,但不能发送多个电子邮件ID,并显示错误。

我刚刚参考了Amazon文档页面并编写了以下代码。

我正在使用环境变量运行团队,它的值类似于['aaa@xyz.com','bbb@xyz.com','ccc@xyz.com']

import boto3
import os
import os, sys, subprocess
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def lambda_handler(event,context):

    ses = boto3.client("ses")
    s3 = boto3.client("s3")
    runemail = os.environ['runteam']
    for i in event["Records"]:
        action = i["eventName"]
        #ip = i["requestParameters"]["soruceIPAddress"]
        bucket_name = i["s3"]["bucket"]["name"]
        object = i["s3"]["object"]["key"]

    fileObj = s3.get_object(Bucket = bucket_name, Key = object)
    file_content = fileObj["Body"].read()

    sender = "test@xyz.com"
    to = runemail
    subject = str(action) + 'Event from ' + bucket_name 

    body = """
        <br>
        This email is to notify regarding {} event
        This object {} is created
    """.format(action,object)

    msg = MIMEMultipart('alternative')

    msg["Subject"] = subject
    msg["From"] = sender
    msg["To"] = ', '.join(runemail)

    body_txt = MIMEText(body, "html")
    attachment = MIMEApplication(file_content)
    attachment.add_header("Content-Disposition","attachment", filename = "ErrorLog.txt")
    msg.attach(body_txt)
    msg.attach(attachment)
    response = ses.send_raw_email(Source = sender, Destinations = rumemail, RawMessage = {"Data": msg.as_string()})
    return "Thanks"

3 个答案:

答案 0 :(得分:1)

我认为有关电子邮件发送代码的一切似乎都正确。错误在于程序中存储环境变量的方式。

应将其存储为runteam="aaa@xyz.com bbb@xyz.com ccc@xyz.com"(注意每封电子邮件之间的空格)

然后将此变量用作
rumemail = os.environ['runteam'].split()

msg["To"] = ', '.join(runemail)

response = ses.send_raw_email(Source = sender, Destinations = rumemail, RawMessage = {"Data": msg.as_string()})

答案 1 :(得分:0)

此行:

msg["To"] = ', '.join(runemail)

需要一个Python列表,而不是字符串。我建议您在其后添加一条调试行,以查看您实际发送的系统。

我建议您将环境变量传递为:

person@address.com, person2@address.com, person3@address.com

然后,使用:

msg["To"] = runemail

答案 2 :(得分:0)

删除/注释以下行应解决此问题:

msg["To"] = ', '.join(runemail)

通过以上一行,您正在将列表转换为字符串。但是,“目标”属性正在寻找列表。