将变量内容打印到电子邮件正文 python 3.7

Print Contents of Variables to body of email python 3.7

正在尝试通过 python 发送电子邮件。可以让它发送正文中包含正确文本内容的电子邮件,但它打印的是实际变量名称 "New Companies" 而不是它的内容。这是代码和生成的电子邮件。

(不知道为什么 html 标签没有出现在我下面的代码中,但我在电子邮件内容前后使用了 html 和 body 标签)

感谢任何帮助。

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

EMAIL_SERVER = 'blahblah'
EMAIL_PORT = 25

f = open('diff.txt', 'r')
NEW_COMPANIES  = f.read()


EMAIL_FROM = 'blabal'
RECIPIENT_LIST = ['blahblah']

msg = MIMEMultipart()
msg['From'] = EMAIL_FROM
msg['To'] = ", ".join(RECIPIENT_LIST)
msg['Subject'] = 'North Carolina New Business Registration'


body = '''<html>
<body>

New Business Names:<br><br>
body.format('NEW_COMPANIES')
<br><br>
Affiliate: r2thek
<br><br>
Website Link: 
https://www.sosnc.gov/online_services/search/by_title/_Business_Registration
</body>
</html>'''

body.format('NEW_COMPANIES')

msg.attach(MIMEText(body, 'html'))


smtpserver = smtplib.SMTP(EMAIL_SERVER, EMAIL_PORT)
smtpserver.sendmail(EMAIL_FROM, RECIPIENT_LIST, msg.as_string())
smtpserver.quit()

电子邮件结果:

新公司名称:

{NEW_COMPANIES}

会员:r2thek

网站Link:https://www.sosnc.gov/online_services/search/by_title/_Business_Registration

您似乎没有传递任何变量来格式化字符串,您需要这样做

body.format(variable1, variable2, etc)

在你的情况下,我认为它只是一个变量,所以无论你存储什么 NEW_COMPANIES 应该需要用作 str.format()

的参数