如何将变量传递给从 Python 发送的 html 电子邮件

How to pass variable to html emails sent from Python

我有这个 python 脚本:

import time
from email.message import EmailMessage

user_age = "12"
user_name="John"

msg = EmailMessage()
msg['Subject'] = "Test Subject"
msg['From'] = 'test@gmail.com'
msg['To'] = 'test2@gmail.com'
msg.set_content("Test Mesage")

html_message = open('test.html').read()
msg.add_alternative(html_message, subtype='html')


while True:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login("test@gmail.com", "pass")
        smtp.send_message(msg)

    time.sleep(500)

我想将变量 first_name、年龄、链接从这个 python 脚本传递到 html 模板 (test.html),访问并将它们格式化为 html。 类似于:

<html>
    <head>
     ....
    </head>
    <body>
        Hei user {{user_name}} we recieved your age confirmation! {{user_age}} is it right?
    </body>
</html>

只需用变量替换您的占位符:

html_message = html_message.replace('{{user_name}}',user_name).replace('{{user_age}}',user_age)
import time
from email.message import EmailMessage

html_message = html_message.replace('{{user_name}}',user_name).replace('{{user_age}}',user_age)

msg = EmailMessage()
msg['Subject'] = "Test Subject"
msg['From'] = 'test@gmail.com'
msg['To'] = 'test2@gmail.com'
msg.set_content("Test Mesage")

html_message = open('test.html').read()
msg.add_alternative(html_message, subtype='html')


while True:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login("test@gmail.com", "pass")
        smtp.send_message(msg)

    time.sleep(500)