Python mail: encoded attachments are truncated
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?
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!
Could it be related to your current base64.MAXBINSIZE
? Encoders.encode_base64
uses base64.encodestring
internally. The default value for base64.MAXBINSIZE
is 57, can always try setting it larger: base64.MAXBINSIZE = 65536
If the file is already written--be sure to .close() the file and re-open()/.read() it for the payload.
My issues stemmed from timing and this solved the issue for me.
精彩评论