我的代码无法完全运行在字典中,我无法弄清楚为什么

时间:2019-06-11 14:28:58

标签: python

我是编码的新手,一直在尝试编写自动的电子邮件格式化程序和发件人,但是在使它意识到已经发送给他人的电子邮件时遇到了麻烦。

我尝试使用如下代码所示的可搜索词典,但是一旦发送一封电子邮件,由于代码中的某些内容而停止。

这只是完整代码的类的一部分,请询问。

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

3 个答案:

答案 0 :(得分:1)

函数执行return语句时,它将立即停止并返回您在return中编写的值。因此,在您的函数中,它将在第一次迭代后停止(因为前行中的return True)。如果希望功能或多或少正确地工作,则应该:

  • 将第一个return False替换为continue。它将跳过所有错误消息。此外,因此,您将不需要else。您只需运行代码即可。
  • 删除最后两行。 return True因为您需要遍历所有消息,return False因为几乎没有意义。

这是最终代码:

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")

答案 1 :(得分:0)

如果我对它的理解正确,那么除非您已经发送过,否则您想向字典self.messages中的每个人发送电子邮件。当前,您需要在一次迭代后调用return,这会终止该函数。

要处理已经发送过电子邮件的情况,请使用continue,它可以简单地跳转到下一个迭代。您还应该删除return True,因为它将终止该功能。如果要布尔返回值,则仅当self.messages中没有消息时才应为false,否则就没有意义了。代码就是这样。

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

答案 2 :(得分:0)

我现在意识到我的错误在于我在该函数顶部迭代的函数中。

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"]