代码之家  ›  专栏  ›  技术社区  ›  Kamer

如何在python中通过电子邮件发送变体?

  •  -1
  • Kamer  · 技术社区  · 2 年前

    如何使用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()\`\`
    

    我试着在变体中加引号并使用字符串: def send_email(): email_body = """ [ { production1: %s %first_element production2: %s %second_element result: %s %result } ] """

    (我是编程新手,所以可能用错了)

    但它不起作用,我希望用户在输入中写的单词被写在电子邮件正文中,而不是变体的名称,例如:如果用户在第一个元素的输入中写test,在第二个元素中写test(1),在结果中写test(2),在正文中是这样的: [ { production1: test production2: test(1) result: test(2) } ]

    1 回复  |  直到 2 年前
        1
  •  0
  •   John Gordon    2 年前

    如果要在字符串消息中包含变量,则有几个选项。

    最简单的方法是使用F字符串格式化消息:

    message = f"Hello {name}, I am glad to meet you."
    

    因为有一个 f 在字符串开头的引号之前,任何用大括号括起来的表达式 {name} {x+y} 将替换为表达式值的字符串表示形式。