电子邮件附件问题

3 投票
1 回答
4045 浏览
提问于 2025-04-15 22:10

我想用以下代码发送一封带附件的邮件(使用Python 3.1),这个例子被大大简化了,方便展示。

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

msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
msg.attach(MIMEText(body))

fp = open(att_file)
msg1 = MIMEText(fp.read())
attachment = msg1.add_header('Content-Disposition', 'attachment', filename=att_file)
msg.attach(attachment)

# set string to be sent as 3rd parameter to smptlib.SMTP.sendmail()
send_string = msg.as_string()

在代码中,附件对象msg1返回的是一个'email.mime.text.MIMEText'对象,但当执行msg1.add_header(...)这一行时,结果却是None。这就导致程序在执行msg.as_string()时出错,因为附件的任何部分都不能是None值。(错误追踪显示在generator.py的第118行出现了"'NoneType'对象没有属性'get_content_maintype'",这个错误发生在msg.as_string()的很多层级下。)

有没有人知道这个问题可能是什么原因呢?任何帮助都会很感激。

Alan Harris-Reid

1 个回答

3

使用:

msg.attach(msg1)

撰写回答