如何使用 python 通过电子邮件发送变体?电子邮件已发送,但未包含变体。这是代码:
\`import email.message import os import smtplib import sys
def restart_program(): python = sys.executable os.execl(python, python, \* sys.argv)
print('Enter the first element:') first_element = (input()) print('Enter the second element:') second_element = (input()) print('Enter the result:') result = (input())
def send_email(): email_body = """ \[ { production1: first_element production2: second_element result: result #I want that the variants: "first_element" "second_element" and "result" be send in the email as the user writes in the input } \] """ from_addr = 'CENSURED' to_addr = 'CENSURED' password = 'CENSURED'
msg = email.message.Message() msg.set_payload(email_body)
server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_addr, password) server.sendmail(from_addr, to_addr, msg.as_string()) server.quit()
print("It's correct?") print(first_element) print("+") print(second_element) print("=") print(result) print('Confirm') Confirm = (input()) if Confirm.lower() == "yes": print("Sending Email...") Send_email() print('Email sent!') restart_program() else: print("Try Again") restart_program()\`\`
I tried putting quotation marks in the variants and using strings:
`def send_email(): email_body = """ [ { production1: %s %first_element production2: %s %second_element result: %s %result } ] """`
(我是编程新手,所以我可能用错了)
但它不起作用,我希望用户在输入中写入的单词写入电子邮件正文中,并插入变体的名称,例如:如果用户在第一个元素的输入中写入 test,则 test(1)在结果的 secondary_element 和 test(2) 中,在正文中如下所示:
[ { production1: test production2: test(1) result: test(2) } ]
如果您想在字符串消息中包含变量,您有多种选择。
最简单的方法是使用 F 字符串格式化消息:
message = f"Hello {name}, I am glad to meet you."
因为字符串开头的引号之前有一个
f
,所以任何用花括号括起来的表达式(如 {name}
)都将替换为该表达式的值。