为什么python要求我在输入后一遍又一遍地输入相同的东西 - (smtpib -gmail)

时间:2014-03-02 07:36:51

标签: python email python-3.x input smtplib

我有这个允许用户发送电子邮件的脚本。但是,当用户对“您是否要发送另一封电子邮件”然后是“是否要切换帐户”是“是”时,为什么登录不起作用?输入不同的用户名和密码后,即使凭据正确,它也会一次又一次地询问。这是我的代码:

end = ("false")
end2 = ("false")
while True:
    if (end == "true"):
        break
    print ("Contacting server...")
    user = smtplib.SMTP('smtp.gmail.com', 587)
    user.starttls()
    while True:
        euser = input("Enter Gmail Username: ")
        epass = input("Enter Gmail Password: ")
        try:
            user.login(euser, epass)
        except smtplib.SMTPAuthenticationError:
            print ("Invalid Credentials!")
            continue
        break
        while True:
            if (end == "true" or end2 == "true"):
                break
            user.login(euser, epass)
            print ("Retrieving Files")
            subjectinput = input("Enter Subject: ")
            msginput = input("Enter Message: ")
            msg = ("\n"+msginput)
            sourcemail = (euser)
            while True:
                targetmail = input("Enter Your Recipient: ")
                try:
                    user.sendmail(sourcemail, targetmail, 'Subject: {}\r\n\r\n{}'.format(subjectinput, msg))
                except (smtplib.SMTPRecipientsRefused):
                    print ("Invalid Recipient!")
                    continue
                break
            user.sendmail(sourcemail, targetmail, 'Subject: {}\r\n\r\n{}'.format(subjectinput, msg))
            print ("Email Sent")
            ask = input("Whould you like to send another one [Y/N]: ")
                if(ask == "n" or ask == "N" or ask == "no" or ask == "No"):
                    end = ("true")
                    break
                if(ask == "y" or ask == "Y" or ask == "yes" or ask == "Yes"):
                    newuser = input("Do you want to switch accounts [Y/N]: ")
                    if (newuser == "n" or newuser == "N" or newuser == "no" or newuser == "No"):
                        continue
                    if (newuser == "y" or newuser == "Y" or newuser == "yes" or newuser == "Yes"):
                        end2 = "true"
                        break

非常感谢任何答案。谢谢,我在python上相当新:)

1 个答案:

答案 0 :(得分:1)

看看这部分:

while True:
    euser = input("Enter Gmail Username: ")
    epass = input("Enter Gmail Password: ")
    try:
        user.login(euser, epass)
    except smtplib.SMTPAuthenticationError:
        print ("Invalid Credentials!")
        continue
    break

当登录成功时,执行的下一个语句是break,并且会将您返回到外部while循环的开头。您需要将break移到try语句中(并且您可以移除continue,因为您现在无论如何都在循环结束时),然后突然出现以下{ {1}}循环使它与前一个循环相同:

while