
本文旨在解决在使用Python发送邮件时,附件文件名中包含空格导致的问题。通过示例代码演示了如何正确地使用引号包裹文件名,从而确保接收方能够正确地识别和预览附件,避免文件名显示不完整或包含URL编码字符。
在使用Python的email库发送带有附件的邮件时,如果附件的文件名包含空格,可能会遇到一些问题。常见的问题是,接收方看到的附件名称不完整(只显示空格前的部分),或者文件名中的空格被URL编码为%20,影响用户体验。
解决这个问题的方法很简单,就是在设置Content-Disposition头部时,使用引号将文件名包裹起来。
以下是一个修改后的代码片段,展示了如何正确地添加附件头部:
立即学习“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
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!")代码解释:
注意事项:
总结:
通过简单地将文件名用引号包裹起来,就可以有效地解决Python邮件附件中包含空格的文件名问题。 这确保了接收方能够正确地识别和预览附件,提升用户体验。 记得关注安全性和错误处理,以构建更健壮的邮件发送应用。
以上就是正确处理Python邮件附件中包含空格的文件名的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号