在HTML电子邮件中使用变量?

DDI*_*Guy 1 python html-email

我正在使用此帖子发送使用Python发送电子邮件的信息

到目前为止,说明是完美的.我还有两件事要做:

  1. 在体内调用变量
  2. 添加附件

变量将是今天的日期.就是这个:

today = datetime.datetime.today ()
tday = today.strftime ("%m-%d-%Y")
Run Code Online (Sandbox Code Playgroud)

我知道使用mailx,您可以使用-a选项附加.

Nav*_*een 5

要调用html体内的变量,只需将它们转换为字符串即可在体内连接它们

from datetime import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

today = datetime.today ()
tday = today.strftime ("%m-%d-%Y")

# email subject, from , to will be defined here
msg = MIMEMultipart()

html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       """ +str(today)+ """ and """ +str(tday)+ """
    </p>
  </body>
</html>
"""
msg.attach(MIMEText(html, 'html'))
Run Code Online (Sandbox Code Playgroud)

有关附件,请查看http://naelshiab.com/tutorial-send-email-python/

  • 如果值是可信的,这只是合理的建议.如果它们包括,例如,`<script>`内容,则不会执行正确的转义以确保插入的内容被视为文本而不是浏览器呈现. (3认同)