How to clear all data in MIMEBase (email module)

so i have this code:

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

in this code, it sends 21 files at a time to avoid exceeding the limit of gmail messages. But the problem is that the data in MIMEBase remains ... my question is, is there a way to delete all the data in MIMEBase? I'm sorry the indent is wrong

+4
source share
1 answer

It seems your problem is that you:

  • Create msg .
  • Add 21 files to msg .
  • Send it.
  • Add another 21 files, so now it has 42 files.
  • Send it again; this second message is twice the size of the first.
  • Add 21 more files, bringing the total to 63.
  • Send it again; Now it is becoming quite huge.
  • Etc.

When a==21 you should start with a new msg object instead of continuing to add more and more files to the old one.

Alternatively, you can try to remove already 21 attached applications before attaching new ones; but just starting up can be simpler, since you already have code to start a new message with the correct headers - it just needs to be refactored in the small function β€œstart a new message”.

+2
source