Python - 电子邮件发送——将变量传递给 HTML 编码器

问题描述 投票:0回答:0

如果我使用示例代码并使用正确的凭据,则原始编码有效。 (如果你想尝试这个,“密码”是在/通过 Gmail 帐户生成的。)

(旧)代码发送静态消息。我要发动态消息

我正在尝试将变量传递到 HTML 正文中...

html_txt = missing_compare_df['名称'].to_list()

if missing_count==0:
    msg = "0 Missing Websites"
    
else:
    'Website Count Error!'


today = date.today()
today = today.strftime('%m-%d-%y')

from_address = "[email protected]"
to_address = "[email protected]"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = msg
msg['From'] = from_address
msg['To'] = to_address
  • (旧)示例代码<- This works!

# Create the message (HTML).
# html = """\
# Scraping & Import Complete - Initiating ML.
# """*

/(旧)示例代码

/ 这不起作用(我正在尝试传递一个变量)

**html = html_txt  

/\ 这行不通 /###

# Record the MIME type - text/html.
part1 = MIMEText(html, 'html')

# Attach parts into message container
msg.attach(part1)

# Credentials
username = '[email protected]'  
password = 'xxxxxxxx'

# Sending the email
## note - this smtp config worked for me, I found it googling around, you may have to tweak the # (587) to get yours to work
server = smtplib.SMTP('smtp.gmail.com', 587) 
server.ehlo()
server.starttls()
server.login(username,password)  
server.sendmail(from_address, to_address, msg.as_string())  
server.quit()
print('email sent')

错误消息说: 单元格 In[43],第 44 行,在 send_email() 中 41 html = html_txt 43 # 记录 MIME 类型 - text/html。 ---> 44 第 1 部分 = MIMEText(html, 'html') 46 # 将部件附加到消息容器中 47 消息.attach(part1)

File ~ naconda3\lib mail\mime ext.py:34, in MIMEText.init(self, _text, _subtype, _charset, policy) 32 如果_charset 为无: 33 尝试: ---> 34 _text.encode('us-ascii') 35 _charset = '我们-ascii' 36 除了 UnicodeEncodeError:

AttributeError: 'list' 对象没有属性 'encode'

python html html-email encode send
© www.soinside.com 2019 - 2024. All rights reserved.