Python中如何处理email.mime.multipart邮件中的附件大小限制
发布时间:2023-12-14 12:01:32
在Python中处理带有附件的邮件时,可以使用email.mime.multipart模块。要限制附件的大小,可以使用MIMEBase类的add_header()方法设置Content-Disposition头部的filesize参数,并在发送邮件之前检查每个附件的大小。
以下是一个处理附件大小限制的示例代码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_email_with_attachment(sender, receiver, subject, body, attachment_path, attachment_size_limit):
# 创建邮件对象
message = MIMEMultipart()
message["From"] = sender
message["To"] = receiver
message["Subject"] = subject
# 添加正文
message.attach(MIMEText(body, "plain"))
# 添加附件
with open(attachment_path, "rb") as file:
attachment = MIMEBase("application", "octet-stream")
attachment.set_payload(file.read())
# 设置附件名称
attachment.add_header("Content-Disposition", "attachment", filename=attachment_path)
# 检查附件大小
if attachment_size_limit is None or len(attachment.get_payload()) <= attachment_size_limit:
# 编码附件,并添加到邮件中
encoders.encode_base64(attachment)
message.attach(attachment)
else:
print(f"附件 {attachment_path} 超过了大小限制")
# 发送邮件
try:
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login(sender, "password")
server.sendmail(sender, receiver, message.as_string())
print("邮件发送成功")
except Exception as e:
print("邮件发送失败:", str(e))
sender = "sender@example.com"
receiver = "receiver@example.com"
subject = "测试邮件"
body = "这是一封测试邮件,请忽略。"
attachment_path = "attachment.pdf"
attachment_size_limit = 1000
send_email_with_attachment(sender, receiver, subject, body, attachment_path, attachment_size_limit)
上述代码中,首先创建一个MIMEMultipart对象作为邮件容器,并设置发件人、收件人和主题等信息。然后,通过open()函数打开要添加为附件的文件,并创建一个MIMEBase对象。接下来,使用add_header()方法设置Content-Disposition头部的filesize参数,检查附件的大小是否超过了设置的限制。如果附件的大小未超过限制,则使用encoders.encode_base64()方法编码附件,并将其添加到邮件中。最后,使用smtplib.SMTP类发送邮件。
注意:为了运行上述代码,需要将示例中的sender@example.com、receiver@example.com和smtp.example.com替换为真实的发件人、收件人和SMTP服务器地址,并将password替换为发件人邮箱的授权码。另外,需要确保attachment.pdf文件存在。
