我有使用tkinter作为我的GUI的程序。我的程序单击一个按钮以发送电子邮件。一旦他们单击该按钮,也会出现一个条目/按钮,以便用户可以输入其电子邮件来发送消息。单击该按钮后,即会将邮件发送到该电子邮件。
但是,当我单击第一个按钮(发送电子邮件)时,我得到了正确的错误:
{'': (555, b'5.5.2 Syntax error. i72sm3973288itc.11 - gsmtp')}
该错误发生在我什至无法在输入框中输入电子邮件地址之前。我正在尝试成功输入电子邮件地址并向该电子邮件发送消息,但到目前为止失败。
这是我的代码:
from tkinter import *
import smtplib
root = Tk()
def create_button():
email_btn = Button(root, text="SEND AN EMAIL", fg='blue',
command=lambda: get_email())
email_btn.pack()
def get_email():
entry_email = StringVar()
entry_email.get()
email = Entry(root, textvariable=entry_email)
email.pack()
send_btn = Button(root, text="SEND", command=send_email_info(entry_email))
send_btn.pack()
def send_email_info(entry_email):
try:
prompt_msg = "THIS IS A MESSAGE FOR THE EMAIL"
user = '*****@gmail.com'
password = '******'
sender = entry_email.get()
subject = "EMAIL TEST "
message = "Subject: {} \n\n{}".format(subject, prompt_msg)
send_to = ("{}".format(sender))
mail = smtplib.SMTP_SSL('smtp.gmail.com', 465)
mail.ehlo()
mail.login(user, password)
mail.sendmail(user, send_to, message)
mail.close()
print("Success Email!")
email_cmd = Label(root, text="Email Sent!")
email_cmd.pack()
except Exception as x:
print("FAILED")
print(x)
def main():
create_button()
root.mainloop()
main()
答案 0 :(得分:3)
首先,您不需要entry_email.get()
,这只是从小部件获取字符串,而且无论如何您都不捕获返回值。您确实需要entry_email.get()
而不是entry_email
作为send_btn
函数的参数。它过早评估的原因是因为您没有像在代码的第一部分中那样使用lambda
函数(就像您每次在函数的回调中包含参数时都应使用)。我认为您正在寻找类似的代码:
from tkinter import *
import smtplib
root = Tk()
def create_button():
email_btn = Button(root, text="SEND AN EMAIL", fg='blue',
command=lambda: get_email())
email_btn.pack()
def get_email():
entry_email = StringVar()
# entry_email.get() # you don't need this, it does nothing
email = Entry(root, textvariable=entry_email)
email.pack()
# function below needs a lambda
send_btn = Button(root, text="SEND", command=lambda: send_email_info(entry_email.get()))
send_btn.pack()
def send_email_info(entry_email):
try:
prompt_msg = "THIS IS A MESSAGE FOR THE EMAIL"
user = '*****@gmail.com'
password = '******'
sender = entry_email
subject = "EMAIL TEST "
message = "Subject: {} \n\n{}".format(subject, prompt_msg)
send_to = ("{}".format(sender))
mail = smtplib.SMTP_SSL('smtp.gmail.com', 465)
mail.ehlo()
mail.login(user, password)
mail.sendmail(user, send_to, message)
mail.close()
print("Success Email!")
email_cmd = Label(root, text="Email Sent!")
email_cmd.pack()
except Exception as x:
print("FAILED")
print(x)
def main():
create_button()
root.mainloop()
main()