我正在使用以下代码发送邮件附件,有时它会成功,但有时会发送一个空文件。我知道文件的读取成功完成。任何人都知道我的代码有什么问题吗?
import smtplib
import os
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
msg = MIMEMultipart()
msg['From'] = **************
msg['To'] = **************
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = “Hi"
msg.attach(MIMEText("text"))
f = "myzip.zip"
fil = open(f, "rb")
x = fil.read()
fil.close()
part = MIMEApplication(x,Name=basename(f))
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
smtp = smtplib.SMTP("127.0.0.1")
smtp.sendmail(“*****************", “********************", msg.as_string())
smtp.close()
编辑: 我注意到,通常当我尝试发送特定文件几次时,第一次通常会成功。