所以我有这个代码:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
def sendMail(to, subject, text, files=[],server="smtp.gmail.com:587"):
assert type(to)==list
assert type(files)==list
fro = "psaoflamand@live.com>"
msg = MIMEMultipart()
msg['From'] = fro
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
a=0
username = 'psaoflamand@gmail.com'
password = 'pass'
# The actual mail send
smtp = smtplib.SMTP(server)
smtp.starttls()
smtp.login(username,password)
for file in files:
a+=1
print a
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
if a==21:
smtp.sendmail(fro, to, msg.as_string() )
a=0
print 'sent'
smtp.quit()
sendMail(
["psaoflamand@live.com"],
"hello","cheers",
["Thousands of one megabyte files"]
Run Code Online (Sandbox Code Playgroud)
在此代码中,它一次发送 21 个文件,以避免超出 Gmail 消息的限制。但问题是 MIMEBase 中的数据保留...我的问题是有没有办法删除 MIMEBase 中的所有数据?抱歉,缩进错误
看起来你的问题是:
\n\nmsg。msg.当a==21您应该从一个新对象开始msg而不是继续向旧对象添加越来越多的文件时。
或者,您可以尝试删除已有的 21 个附件,然后再附加新的附件;但重新开始可能会更简单,因为您已经有了使用正确的标头 \xe2\x80\x94 启动新消息的代码,它只需要重构为一点 \xe2\x80\x9cstart a new message\xe2\ x80\x9d 函数。
\n