用户选择 emailProvider,但程序不会定义变量

问题描述

我正在从头开始编写我的第一个 Python 程序;它根据用户输入的每个变量编写和发送电子邮件。要定义的第一个变量是用户的电子邮件服务器,其内容如下:

# Establish email server connection
print('Welcome to Brett\'s email program! Let\'s send a message.')
emailServer = input('First,I need your email provider: Gmail,Yahoo,or Outlook?\n')

用户输入他们的电子邮件提供商,然后从这个列表中命名变量:

if emailServer == 'Gmail':
    emailProvider = 'smtp.gmail.com'
if emailServer == 'Yahoo!':
    emailProvider = 'smtp.mail.yahoo.com'
if emailServer == 'Yahoo':
    emailProvider = 'smtp.mail.yahoo.com'
if emailServer == 'Outlook':
    emailProvider = 'smtp.office365.com' # Found this server name on serversmtp.com
# Todo: Test other email providers (iCloud,AT&T,Comcast,Verizon)
else:
    print('I don\'t kNow that email provider. Please try again.')

在这种情况下,每次我运行程序时,我都会收到 else 语句(“我不知道那个电子邮件提供商。”),然后程序会继续询问电子邮件地址。

我尝试了几种不同的方法来处理这些 if/else 语句。我做过 elif 语句、continue 语句、break 语句,甚至是这样的布尔语句:

if emailServer == 'Gmail' = True:
        emailProvider = 'smtp.gmail.com'

它们都不起作用。如果我将 Gmail 设为 emailProvider 的认值,该程序确实可以工作,所以我知道这是错误部分。

如何使该部分起作用?我认为将电子邮件提供商信息放在字典中可能会奏效,但我不知道如何实现。作为一名开发人员,我仍在学习,因此举一个如何组织代码的示例(字典条目、正确的 elif 语句)对理解大有帮助。谢谢。

解决方法

试试if... elif... else...

print('Welcome to Brett\'s email program! Let\'s send a message.')
emailServer = input('First,I need your email provider: Gmail,Yahoo,or Outlook?\n')

if emailServer == 'Gmail':
    emailProvider = 'smtp.gmail.com'
elif emailServer == 'Yahoo!':
    emailProvider = 'smtp.mail.yahoo.com'
elif emailServer == 'Yahoo':
    emailProvider = 'smtp.mail.yahoo.com'
elif emailServer == 'Outlook':
    emailProvider = 'smtp.office365.com'
else:
    print('I don't know that email provider. Please try again.')
,

谢谢,伊斯梅尔。该修复允许 Gmail 选项正常工作并继续执行该程序。当我使用 Yahoo! 时,我确实收到了这个消息块。作为 emailProvider:

File "/home/pi/mu_code/emailSenderTest/emailSenderTest.py",line 56,in <module>
    conn.login(userName,password)
  File "/usr/lib/python3.7/smtplib.py",line 721,in login
    initial_response_ok=initial_response_ok)
  File "/usr/lib/python3.7/smtplib.py",line 631,in auth
    (code,resp) = self.docmd("AUTH",mechanism + " " + response)
  File "/usr/lib/python3.7/smtplib.py",line 421,in docmd
    return self.getreply()
  File "/usr/lib/python3.7/smtplib.py",line 394,in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

任何人都知道这意味着什么或如何制作 Yahoo!功能工作。我的端口设置为 587。