Home > Software engineering >  Dynamic text to be sent using MIMEMultipart and SES service in lambda
Dynamic text to be sent using MIMEMultipart and SES service in lambda

Time:04-13

I am using lambda to send a raw message from SES.

def send_email_method(p1, p2):
    msg = MIMEMultipart()
    msg["Subject"] = "Test123"
    msg["From"] = "[email protected]"
    msg["To"] = "[email protected]"

    
    body = MIMEText("Find list of activity. Part 1="  p1  "Part 2="   p2, "html") /** Here according to 3 conditions below data should be sent**/
    msg.attach(body)
        
    ses_client = boto3.client("ses", region_name="us-west-1")
    response = ses_client.send_raw_email(
        Source="[email protected]",
        Destinations=["[email protected]"],
        RawMessage={"Data": msg.as_string()}
    )
    return

def lambda_handler(event, context):
    p1=os.environ['p1']
    p2=os.environ['p2']
    send_email_method(p1, p2)

The p1 and p2 environment vars can have following values :-

  1. p1='sketch', p2='draw'---- In this case both p1 & p2 should be mentioned in mail
  2. p1='', p2='draw'---- In this case only p2 should be mentioned in mail as p1 is empty
  3. p1='sketch', p2=''----In this case only p1 should be mentioned in mail as p2 is empty

How can the above 3 conditions be achieved in the above code keeping in mind that these p1 & p2 can extend to p3,p4 and p5 as well??

CodePudding user response:

The simplest method would be to use some if statements to construct your message.

However, since the number of variables could increase in future, I'd recommend changing the program to pass a dictionary to the send_email_method() function, which will allow any number of inputs. The function could then loop through the dictionary and construct the string, something like:

values = {1: "sketch", 2: "draw", 3:"erase", 4:"rotate"}

message = ""

for value in values:
  message  = f" Part {value}={values[value]}"
  • Related