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

2024-10-02 00:36:33 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这个代码:

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"]

在这段代码中,它一次发送21个文件,以避免超过gmail邮件的限制。但问题是MIMEBase中的数据。。。我的问题是有没有一种方法可以删除MIMEBase中的所有数据?很抱歉,压痕错了


Tags: tofromimportcomemailmsgfilessmtp
1条回答
网友
1楼 · 发布于 2024-10-02 00:36:33

看来你的问题是:

  1. 创建一个msg。在
  2. msg追加21个文件。在
  3. 把它送过来。在
  4. 附加21个文件,这样它现在有42个附加文件。在
  5. 再发一次,这第二条消息比第一条大两倍。在
  6. 追加21个文件,总数达到63个。在
  7. 再发一次吧,现在越来越大了。在
  8. 等等。在

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

或者,您可以尝试在附加新的附件之前删除已经存在的21个附件;但是重新开始可能会更简单,因为您已经准备好了启动具有正确标头的新邮件的代码—它只需要重构为一个小的“start a new message”函数。在

相关问题 更多 >

    热门问题