Skip to content

Instantly share code, notes, and snippets.

@kuharan
Created February 14, 2021 05:37
Show Gist options
  • Save kuharan/4daf9b97926b8e2c1c565610ace1115c to your computer and use it in GitHub Desktop.
Save kuharan/4daf9b97926b8e2c1c565610ace1115c to your computer and use it in GitHub Desktop.
Send email with attachments in AWS lambda
def send_email(sender, recipient, aws_region, subject, file_name):
# The email body for recipients with non-HTML email clients.
BODY_TEXT = "Hello,\r\nPlease find the attached file."
# The HTML body of the email.
BODY_HTML = """\
<html>
<head></head>
<body>
<h1>Hello!</h1>
<p>Please find the attached file.</p>
</body>
</html>
"""
CHARSET = "utf-8"
client = boto3.client('ses',region_name=aws_region)
msg = MIMEMultipart('mixed')
# Add subject, from and to lines.
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
msg_body = MIMEMultipart('alternative')
textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)
# Add the text and HTML parts to the child container.
msg_body.attach(textpart)
msg_body.attach(htmlpart)
# Define the attachment part and encode it using MIMEApplication.
att = MIMEApplication(open(file_name, 'rb').read())
att.add_header('Content-Disposition','attachment',filename="xxx_info.json")
if os.path.exists(file_name):
print("File exists")
else:
print("File does not exists")
# Attach the multipart/alternative child container to the multipart/mixed
# parent container.
msg.attach(msg_body)
# Add the attachment to the parent container.
msg.attach(att)
try:
#Provide the contents of the email.
response = client.send_raw_email(
Source=msg['From'],
Destinations=[
msg['To']
],
RawMessage={
'Data':msg.as_string(),
}
)
# Display an error if something goes wrong.
except ClientError as e:
return(e.response['Error']['Message'])
else:
return("Email sent! Message ID:", response['MessageId'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment