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

时间:2018-08-29 15:49:49

标签: python html smtplib email-formats

试图通过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

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

1 个答案:

答案 0 :(得分:0)

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

body.format(variable1, variable2, etc)

在您的情况下,我认为这只是一个变量,因此无论您存储在哪里,都应将NEW_COMPANIES用作str.format()的参数