
本文旨在解决在使用Python发送邮件时,附件文件名包含空格导致显示异常的问题。通过在`Content-Disposition`头部中对文件名进行适当的引用,确保接收方能够正确识别和处理带有空格的文件名,从而避免文件名截断或显示错误的问题。
在使用Python的email模块发送带有附件的邮件时,如果附件文件名包含空格,可能会遇到接收方显示的文件名不完整或出现乱码的问题。这是因为某些邮件客户端在解析Content-Disposition头部时,对未正确转义或引用的空格处理不当。以下提供一种解决方案,确保文件名中的空格能够被正确处理。
问题分析
当文件名包含空格时,直接将其放入Content-Disposition头部可能会导致问题。例如,文件名 my attachment.pdf 可能会被邮件客户端截断为 my。虽然将空格替换为 %20 可以避免截断,但接收方会看到 %20 出现在文件名中,影响用户体验。
立即学习“Python免费学习笔记(深入)”;
解决方案
最有效的解决方案是将文件名用双引号括起来。这样,即使文件名中包含空格,邮件客户端也能正确解析。
代码示例
以下是修改后的代码片段:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os
def prepare_attachment(filepath):
filename = os.path.basename(filepath)
attachment = open(filepath, "rb")
# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form.
p.set_payload((attachment).read())
# encode into base64
encoders.encode_base64(p)
# 将文件名用双引号括起来
p.add_header('Content-Disposition', 'attachment; filename="%s"' % filename)
return p
class Sender(object):
def __init__(self, sender_email, sender_password, recipient_email, attachments):
self.sender_email = sender_email
self.sender_password = sender_password
self.recipient_email = recipient_email
self.attachments = attachments
def send(self):
msg = MIMEMultipart()
msg['From'] = self.sender_email
msg['To'] = self.recipient_email
msg['Subject'] = "Email with attachments"
body = "This is the email body with attachments."
msg.attach(MIMEText(body, 'plain'))
# open the file to be sent
for attachment in self.attachments:
p = prepare_attachment(attachment)
# attach the instance 'p' to instance 'msg'
msg.attach(p)
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login(self.sender_email, self.sender_password)
# Converts the Multipart msg into a string
text = msg.as_string()
# sending the mail
s.sendmail(self.sender_email, self.recipient_email, text)
# terminating the session
s.quit()
# 示例用法
if __name__ == '__main__':
sender_email = "your_email@gmail.com" # 你的邮箱地址
sender_password = "your_password" # 你的邮箱密码 (建议使用应用专用密码)
recipient_email = "recipient_email@example.com" # 收件人邮箱地址
attachments = ["my attachment.pdf", "another file with space.txt"] # 包含空格的文件名
sender = Sender(sender_email, sender_password, recipient_email, attachments)
sender.send()
print("邮件已发送!")代码解释
关键在于 p.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) 这一行。 通过将 %s 用双引号包围,确保 filename 变量中的空格被正确处理。
注意事项
总结
通过将文件名用双引号括起来,可以有效解决Python邮件附件中文件名包含空格导致的问题。这种方法简单易行,且兼容性较好。在编写邮件发送程序时,务必注意处理文件名中的特殊字符,以确保邮件能够被正确解析和显示。
以上就是正确处理Python邮件附件中的空格文件名的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号