You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现带附件自动发送邮件时遭遇AttributeError: 'list' object has no attribute 'encode'错误的技术咨询

解决Python邮件发送中的AttributeError: 'list' object has no attribute 'encode'错误

嘿,我一眼就揪出问题所在了——你在设置邮件的To头部时犯了个容易忽略的小错误!

错误原因

message['To']字段要求的是逗号分隔的字符串格式(符合邮件标准的收件人格式),但你直接把Python列表receiver_email赋值给它了。当邮件库尝试对这个字段进行编码(encode)操作时,列表对象没有这个方法,就抛出了你看到的AttributeError。

修复步骤

1. 修正收件人头部赋值

把这行:

message ['To'] = receiver_email

改成:

message['To'] = ', '.join(receiver_email)

这会把你的收件人列表转换成"a@example.com, b@example.com"这样的字符串,完全符合邮件头的要求。

2. 修复附件的Header参数(隐藏坑)

你写的Content-Decomposition是错误的,正确的参数名是Content-Disposition,否则附件可能无法正常显示:

payload.add_header('Content-Disposition', 'attachment', filename=attach_file_name)

3. 优化文件读取(可选但更安全)

用with语句读取收件人文件,它会自动帮你关闭文件,避免资源泄漏,还可以顺便过滤空行:

with open("receiver_list.txt", "r") as f:
    receiver_email = [i.strip() for i in f.readlines() if i.strip()]

完整修正后的代码

import email, smtplib, ssl, getpass, stdiomask
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# 获取发件人邮箱
sender_email = input("Please input email: ")
password = stdiomask.getpass("Input your password: ")
mail_content = "Hi this sent from Python"

# 读取收件人列表(优化版)
with open("receiver_list.txt", "r") as f:
    receiver_email = [i.strip() for i in f.readlines() if i.strip()]

message = MIMEMultipart()
message['From'] = sender_email
# 修复To字段:列表转逗号分隔字符串
message['To'] = ', '.join(receiver_email)
message['Subject'] = 'Python Email'
message.attach(MIMEText(mail_content, 'plain'))

attach_file_name = 'Final Project - Basic Python.pdf'
attach_file = open(attach_file_name, 'rb')
payload = MIMEBase('application', 'octet-stream')  # 修正笔误:octate-stream → octet-stream
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)
# 修复Header参数名
payload.add_header('Content-Disposition', 'attachment', filename=attach_file_name)
message.attach(payload)

# 登录服务器发送邮件
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)
    text = message.as_string()
    server.sendmail(sender_email, receiver_email, text)
print('Mail Sent')

另外我还修正了一个小笔误:octate-stream应该是octet-stream,虽然可能不影响运行,但规范一点更好。

现在运行代码应该就能正常读取收件人列表并发送带附件的邮件啦!

内容的提问来源于stack exchange,提问作者RoboData

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:24:09