Skip to main content
 首页 » 编程设计

python之在 HTML 电子邮件中使用变量

2025年05月04日29yjmyzz

我正在使用在这篇文章中找到的信息 Sending Email Using Python

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

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

变量将是今天的日期。就是这样:

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

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

请您参考如下方法:

要在html body中调用变量,只需将它们转换为字符串以在body中连接它们

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')) 

附件请看http://naelshiab.com/tutorial-send-email-python/

编辑: 上面提供的链接似乎不可用,因此通过电子邮件(特别是来自 gmail)发送附件的代码片段如下

import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase 
from email import encoders 
 
msg = MIMEMultipart() 
 
msg['From'] = "from email address" 
msg['To'] = "to email address"  
msg['Subject'] = "Subject line"  
body = """Body  
          content""" 
 
msg.attach(MIMEText(body, 'plain')) 
attachment = open("/path/to/file", "rb")  
p = MIMEBase('application', 'octet-stream')  
 
# To change the payload into encoded form  
p.set_payload((attachment).read())  
 
# encode into base64  
encoders.encode_base64(p)  
 
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)  
 
# attach the instance 'p' to instance 'msg'  
msg.attach(p)  
 
s = smtplib.SMTP('smtp.gmail.com', 587)  
s.starttls() # for security 
s.login("from email address", "your password")  
 
text = msg.as_string()  
 
# sending the mail  
s.sendmail("from email address", "to email address" , text) 
s.quit()  

注意:Google 有时会阻止从其他应用程序(安全性较低的应用程序)登录,因此需要在您的 Google 帐户设置中允许此访问 https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none