Python mail: encoded attachments are truncated
Question: I'm using the following function to send an email message with two attachments
in my python script:

    
    
    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
    
    ...
    
    def sendMail(sender_name, to, subject, text, files=None,server="localhost"):
          assert type(to)==list
          if files:
            assert type(files)==list
          print "Files: ",files
          fro = sender_name
    
          msg = MIMEMultipart()
          msg['From'] = fro
          msg['To'] = COMMASPACE.join(to)
          msg['Date'] = formatdate(localtime=True)
          msg['Subject'] = subject
    
          msg.attach( MIMEText(text) )
    
          if files:
            for file in files:
    # ************** File attaching - Start **************
                    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)
    # ************** File attaching - End **************
    
          server.set_debuglevel(1)
          server.ehlo()
          server.starttls()
          server.ehlo()
          server.sendmail(fro, to, msg.as_string())
          server.quit()
    

I get the mail, and the attachments are there, but for some reason, they are
truncated a bit. My guess is I'm missing something in the encoding process.

For example:

Attachment 1: Original file byte count is 1433902, while the new byte count is
1433600

Attachment 2: Original file byte count is 2384703, while the new byte count is
2383872

Any ideas?


Answer: Found the problem. Turns out I tried sending the files before the buffer of
the writing process was fully flushed.

So, it was a synchronization issue and not an encoding issue.

Sorry about that, and thanks for the help guys!

