我有這個 python 腳本:
import time
from email.message import EmailMessage
user_age = "12"
user_name="John"
msg = EmailMessage()
msg['Subject'] = "Test Subject"
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
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("[email protected]", "pass")
smtp.send_message(msg)
time.sleep(500)
我想傳遞一個變數,如 first_name、age、從這個 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>
uj5u.com熱心網友回復:
只需用變數替換占位符:
html_message = html_message.replace('{{user_name}}',user_name).replace('{{user_age}}',user_age)
uj5u.com熱心網友回復:
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'] = '[email protected]'
msg['To'] = '[email protected]'
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("[email protected]", "pass")
smtp.send_message(msg)
time.sleep(500)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391228.html
