Reputation: 85
I am new to AWS Lambda function.
I wanted to send email to multiple recipients. I am able to send email to single email address but not multiple email ids and shows error.
I just refered the amazon documentation page and wrote the below code.
I am using environmental variable runteam and it has values like ['[email protected]','[email protected]','[email protected]']
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 = "[email protected]"
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"
Upvotes: 1
Views: 6502
Reputation: 753
I think everything seems to be right regarding the email sending code. The error lies in your program where the way you store your environ variable.
It should be stored as runteam="[email protected] [email protected] [email protected]"
(notice the space between each email)
Then use this variable as
rumemail = os.environ['runteam'].split()
msg["To"] = ', '.join(runemail)
response = ses.send_raw_email(Source = sender, Destinations = rumemail, RawMessage = {"Data": msg.as_string()})
Upvotes: 3
Reputation: 71
Removing/commenting out the following line should fix the issue:
msg["To"] = ', '.join(runemail)
By the above line, you are converting a list to a string. However, Destinations attribute is looking for a list.
Upvotes: 0
Reputation: 270134
This line:
msg["To"] = ', '.join(runemail)
is expecting a Python list, not a string. I suggest you add a debug line after it to see what you are actually sending the system.
I would recommending passing your environment variable as:
[email protected], [email protected], [email protected]
Then, use:
msg["To"] = runemail
Upvotes: 2