Search code examples
pythonloopsreturn-value

Storing the returned values of calling a function in a loop in a list


I have two functions:

  1. SendMail(to, f_name, table ) - it sends a mail to the recipient using smtplib. Code snippet:

    def SendMail(to, f_name, table )
        # ...
    
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_password)
        print("Type 'Y' to send the mail! ")
        text = input(">")
        if text.lower() == "y":
            #print("Sending mail")
            server.sendmail(gmail_user, to, msg.as_string())
            print("Mail sent to "+ first_name)
            server.close()
            status = 'success'
            return status
        else:
            print("Mail NOT sent to " + first_name)
            status = 'fail'
            return status
    
  2. MailLoop(): I have a list of people that I'm sending a customised mail to.

    def MailLoop():
        for owner in owner_list:
            to = 'somemailaddress'
            f_name = 'somefirstname'
            table = 'sometable'
            SendMail(to, f_name, table)
    

How can I pass the value of status that is returned from the SendMail(to, f_name, table ) function after each iteration to the outer MailLoop() function?

I would like to store the status of each iteration in a list so that I can see and print the result after the MailLoop() function is finished.


Solution

  • Return a list from MailLoop:

    def MailLoop():
        statuses = []
        for owner in owner_list:
            to = 'someemailaddress'
            f_name = 'somefirstname'
            table = 'sometable'
            statuses.append(SendMail(to, f_name, table))
        return statuses