简体   繁体   中英

My code wont fully run through my dictionary and i cant figure out why

I am new to coding and have been trying to write an automated email formater and sender but am running into trouble trying to get it to realise when it has already sent someone an email.

I tried using a searchable dictionary as shown in the code below however once it sends one email it stops due to something in the code.

This is only a segment of a class for the full code please ask.

def send_email(self):
    self.message_format()
    if len(self.messages) > 0:
        for i in self.messages:
            user_email = self.messages[i]["email"]
            user_msg = self.messages[i]["message"]
            if i in self.sent_to_list:
                return False
            else:
                try:
                    email_conn = smtplib.SMTP(host,port)
                    email_conn.ehlo()
                    email_conn.starttls()
                    email_conn.login(username, password)
                    the_msg = MIMEMultipart("alternative")
                    the_msg["Subject"] = "Hello there!"
                    the_msg["From"] = from_email
                    the_msg["To"] = user_email
                    right_msg = MIMEText(user_msg, "plain")
                    the_msg.attach(right_msg)
                    email_conn.sendmail(from_email, [user_email], the_msg.as_string())
                    email_conn.quit()
                    self.sent_to_list[str(i)] = self.messages[i]
                except smtplib.SMTPException:
                    print("Error sending message")
                except smtplib.SMTPAuthenticationError:
                    print("An error occured during login")
            return True
    return False

When your function executes return statement, it immediately stops and returns the value you wrote in return . So in your function it will stop after the first iteration (because of return True in the pre-last line). If you want your function to work more or less correctly, you should:

  • Replace the first return False with continue . It will skip every bad message. Moreover, because of this you will not need else . You can just have your code to work.
  • Remove two last lines. return True because you need to iterate through all messages, return False because it has nearly no sense.

Here is the final code:

def send_email(self):
    self.message_format()
    if len(self.messages) > 0:
        for i in self.messages:
            user_email = self.messages[i]["email"]
            user_msg = self.messages[i]["message"]
            if i in self.sent_to_list:
                continue
            try:
                email_conn = smtplib.SMTP(host,port)
                email_conn.ehlo()
                email_conn.starttls()
                email_conn.login(username, password)
                the_msg = MIMEMultipart("alternative")
                the_msg["Subject"] = "Hello there!"
                the_msg["From"] = from_email
                the_msg["To"] = user_email
                right_msg = MIMEText(user_msg, "plain")
                the_msg.attach(right_msg)
                email_conn.sendmail(from_email, [user_email], the_msg.as_string())
                email_conn.quit()
                self.sent_to_list[str(i)] = self.messages[i]
            except smtplib.SMTPException:
                print("Error sending message")
            except smtplib.SMTPAuthenticationError:
                print("An error occured during login")

If I understand it correctly you want to send emails to everyone in the dictionary self.messages unless you have already sent it. Currently you call return after one iteration, which terminates the function.

To handle cases where you have already sent an email use continue which simple jumps to the next iteration. You should also remove the return True since it will terminate the function. If you want a boolean return value it should be false only if there are no messages in self.messages, otherwise it doesn't really make sense. The code would then be.

def send_email(self):
    self.message_format()
    if len(self.messages) > 0:
        for i in self.messages:
            user_email = self.messages[i]["email"]
            user_msg = self.messages[i]["message"]
            if i in self.sent_to_list:
                continue
            try:
                email_conn = smtplib.SMTP(host,port)
                email_conn.ehlo()
                email_conn.starttls()
                email_conn.login(username, password)
                the_msg = MIMEMultipart("alternative")
                the_msg["Subject"] = "Hello there!"
                the_msg["From"] = from_email
                the_msg["To"] = user_email
                right_msg = MIMEText(user_msg, "plain")
                the_msg.attach(right_msg)
                email_conn.sendmail(from_email, [user_email], the_msg.as_string())
                email_conn.quit()
                self.sent_to_list[str(i)] = self.messages[i]
            except smtplib.SMTPException:
                print("Error sending message")
            except smtplib.SMTPAuthenticationError:
                print("An error occured during login")
        return True
    return False

I realise now that my error was in the function I iterate at the top of that function.

def message_format(self):
    if len (self.user_details) > 0:
        for details in self.get_details():
            name = details["name"]
            date = details["date"]
            total = details["total"] 
            finished_msg = self.base_message.format(
                    name = name,
                    date = date,
                    total = total
                )
            user_email = details.get("email")
            if user_email:
                user_data = {"email": user_email,
                 "message": finished_msg
            }
            self.messages["customer_" + str(len(self.messages)+1)] = user_data
        return self.messages
    else:
        return ["No user data given"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM