如何清除MIMEBase(电子邮件模块)中的所有数据

P's*_*sao 5 python email

所以我有这个代码:

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 中的所有数据?抱歉,缩进错误

Bra*_*des 3

看起来你的问题是:

\n\n
    \n
  1. 创建一个msg
  2. \n
  3. 将 21 个文件附加到msg.
  4. \n
  5. 发送。
  6. \n
  7. 再追加 21 个文件,现在已附加 42 个文件。
  8. \n
  9. 再发一次; 第二条消息是第一条消息的两倍。
  10. \n
  11. 再追加 21 个文件,使总数达到 63 个。
  12. \n
  13. 再发一次; 现在已经变得相当巨大了。
  14. \n
  15. 等等。
  16. \n
\n\n

a==21您应该从一个新对象开始msg而不是继续向旧对象添加越来越多的文件时。

\n\n

或者,您可以尝试删除已有的 21 个附件,然后再附加新的附件;但重新开始可能会更简单,因为您已经有了使用正确的标头 \xe2\x80\x94 启动新消息的代码,它只需要重构为一点 \xe2\x80\x9cstart a new message\xe2\ x80\x9d 函数。

\n