正确处理Python邮件附件中包含空格的文件名

心靈之曲
发布: 2025-10-12 10:35:20
原创
202人浏览过

正确处理python邮件附件中包含空格的文件名

本文旨在解决在使用Python发送邮件时,附件文件名中包含空格导致的问题。通过示例代码演示了如何正确地使用引号包裹文件名,从而确保接收方能够正确地识别和预览附件,避免文件名显示不完整或包含URL编码字符。

在使用Python的email库发送带有附件的邮件时,如果附件的文件名包含空格,可能会遇到一些问题。常见的问题是,接收方看到的附件名称不完整(只显示空格前的部分),或者文件名中的空格被URL编码为%20,影响用户体验。

解决这个问题的方法很简单,就是在设置Content-Disposition头部时,使用引号将文件名包裹起来。

以下是一个修改后的代码片段,展示了如何正确地添加附件头部:

立即学习Python免费学习笔记(深入)”;

Google Antigravity
Google Antigravity

谷歌推出的AI原生IDE,AI智能体协作开发

Google Antigravity 277
查看详情 Google Antigravity
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
    p = MIMEBase('application', 'octet-stream')

    # To change the payload into encoded form
    p.set_payload((attachment).read())

    # encode into base64
    encoders.encode_base64(p)

    # Add header with filename in quotes
    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"
        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()


# Example Usage:
if __name__ == '__main__':
    # Replace with your actual email and password.  Consider using environment variables for security.
    sender_email = "your_email@gmail.com"
    sender_password = "your_password"  # Use a app password if using Gmail
    recipient_email = "recipient_email@example.com"
    attachments = ["my attachment.pdf", "another file with spaces.txt"] # Create dummy files with these names

    sender = Sender(sender_email, sender_password, recipient_email, attachments)
    sender.send()
    print("Email Sent!")
登录后复制

代码解释:

  1. prepare_attachment(filepath) 函数:
    • 接收文件路径作为参数。
    • 从文件路径中提取文件名。
    • 创建MIMEBase对象,用于封装附件数据。
    • 读取附件内容并进行Base64编码。
    • 关键修改: 使用p.add_header('Content-Disposition', 'attachment; filename="%s"' % filename),用双引号将文件名包裹起来。
  2. Sender 类:
    • 包含初始化方法 __init__,接收发件人邮箱、密码、收件人邮箱和附件列表。
    • send 方法负责构建邮件内容,包括正文和附件,并发送邮件。

注意事项:

  • 安全性: 不要将密码硬编码在代码中。 使用环境变量配置文件来存储敏感信息。
  • Gmail App Password: 如果你使用的是Gmail,并且启用了两步验证,你需要创建一个应用专用密码 (App Password) 并在代码中使用它。
  • 异常处理: 建议添加异常处理机制(例如 try...except 块)来捕获可能发生的错误,例如文件不存在或网络连接问题。
  • 编码: 确保你的代码文件使用UTF-8编码,以正确处理文件名中的特殊字符。

总结:

通过简单地将文件名用引号包裹起来,就可以有效地解决Python邮件附件中包含空格的文件名问题。 这确保了接收方能够正确地识别和预览附件,提升用户体验。 记得关注安全性和错误处理,以构建更健壮的邮件发送应用。

以上就是正确处理Python邮件附件中包含空格的文件名的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号