Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error while sending an email in Lambda (python) due to smtp

I have the following code in a lambda:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

def lambda_handler(event, context):
    msg_email = MIMEMultipart('alternative')
    msg_email.attach(MIMEText("mymessage", 'plain'))
    msg_email['Subject'] = subject
    msg_email['From'] = "from@mail.com"
    msg_email['To'] = "to@mail.com"
    try:
        print("AAAA")
        with smtplib.SMTP('email-smtp.eu-west-1.amazonaws.com', 587) as smtp_server:
            print("BBBB")
            smtp_server.ehlo()
            smtp_server.starttls()
            smtp_server.ehlo()
            smtp_server.login('myid', 'mypass')
            smtp_server.sendmail("from@mail.com", "to@mail.com", msg_email.as_string())
    except Exception:
        print("Couldn't send message.")
        raise
    else:
        print("Email sent!")

This code prints "AAAA", but before printing "BBBB" I get an error executing the lambda: Task timed out after 3.01 seconds. However, if I run it in my EC2 instance works fine. Why lambda cannot execute it?

EDIT: The role of the lambda has these permissions: AWSLambdaBasicExecutionRole(with some uiid after it), pinpoint-email-ers-, AmazonSESFullAccess, AmazonWorkMailFullAccess, AmazonWorkMailMessageFlowFullAccess

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Lambda in a VPC does not have internet connection if you place it in a public subnet. It must be placed in a private subnet, which has route table with routes pointing to a NAT gateway. The NAT will be placed in the public subnet.

The details are described in AWS Docs:

Alternatively, just don’t place your lambda in a VPC if you don’t have to.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading