【问题标题】:Python AtributeError _io.TextIOWrapper' object has no attribute 'encode'Python AtributeError _io.TextIOWrapper' 对象没有属性'encode'
【发布时间】:2022-01-21 16:29:15
【问题描述】:

我正在编写一个代码,将电子邮件从 .xlsx 文件发送到邮件列表。

我希望从单独的 .html 文件导入电子邮件正文,但是当它到达第 47 行时出现编码错误 (htmlPart = MIMEText(f, 'html'))

'_io.TextIOWrapper' 对象没有属性'encode'

这是我的代码:

from email.message import Message
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
  
your_email = "XXXXX"
your_password = "XXXXX"
  
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(your_email, your_password)

message = MIMEMultipart("alternative")

email_list = pd.read_excel(r"C:\\Users\\fernando.martinez\\Desktop\\MAILS2.xlsx")
  
names = email_list['Name']
emails = email_list['Mail']
for i in range(len(emails)):
  
    name = names[i]
    email = emails[i]
  
    message = MIMEMultipart("alternative")

    message['From'] = your_email
    message['To'] = email
    message['Subject'] = "SUBJECT HERE"

    with open('emails.html', 'r') as f: 
        html_string = [line.rstrip('\n') for line in f]

    htmlPart = MIMEText(f, 'html')

    message.attach(htmlPart)

    server.send_message(message)

server.close()

【问题讨论】:

  • 请提供完整的追溯信息,说明您的代码(或导入的模块)中的哪一行触发了此错误。
  • 到达第47行时触发错误:htmlPart = MIMEText(f, 'html')

标签: python html pandas email encode


【解决方案1】:

with 在其缩进块的范围内打开和关闭文件。 htmlPart 不在块内 - 因此文件句柄 f 不再与打开的文件关联。

但是 - MIMEText() 需要一个文本字符串,而不是文件句柄,因为它是第一个参数。鉴于您在块内从f 生成html_string,我希望您实际上是指MIMEText(html_string, 'html')

【讨论】:

    猜你喜欢
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2021-05-31
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多