【发布时间】:2021-10-04 21:14:54
【问题描述】:
所以我编写了这段代码,它发送我在输入字段中键入的消息。问题是我希望能够在输入字段中键入多行。该代码应该输入多行,但只是将最后一行发送到我的电子邮件。
这是我的代码:
# modules
import smtplib
from email.message import EmailMessage
ans1 = input("Your gmail address: ")
ans0 = input("Your gmail password(Not shown): ")
ans = input("Name of game: ")
print("Enter/Paste your code. Ctrl-D to send it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
# content
sender = ans1
reciever = "rockzombie005@gmail.com"
password = ans0
msg_body = line
# action
msg = EmailMessage()
msg['subject'] = ans
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender,password)
smtp.send_message(msg)
print("Program sent successfully!")
当我运行我的代码时,它只向我发送最后一行:
代码输出
Your gmail address: *******@gmail.com
Your gmail password(Not shown): ********
Name of game: GAME
Enter/Paste your code. Ctrl-D to send it.
Line 1
Line 2 (end)
Program sent successfully!
GMAIL:
Line 2 (end)
【问题讨论】:
-
您发送的是
line,而不是contents。line包含最后一行,contents是所有行的列表。 -
用你自己的话说,你在哪里
msg_body = line,你觉得会是什么结果?用您自己的话来说,contents在您的代码中的用途是什么?在准备好之后,您是否在代码中看到使用该值的任何内容? -
@Barmar 这显然是一个错字,为什么不关闭这个问题呢?
-
@KarlKnechtel 如果它只是错误的变量,我会有。但由于它还需要加入才能将列表转换为字符串,所以我觉得它足以提供答案。
-
嗯,很公平。