Email attachments

Facundo Batista facundo at
Thu Jan 25 19:09:29 CET 2007

Steve Holden wrote:

> I'm having some trouble getting attachments right for all recipients, 
> and it seems like Apple's is the pickiest client at the moment. 
> It doesn't handle attachments that both Thunderbird and Outlook find 
> perfectly acceptable.

The following code works ok with Thunderbird and (at least with
all the mail I usually sent).

A friend of mine reports that he (with can see that he has an
attachment, open it, etc.)


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

class MailSender:
    '''Envia un mail con archivos attached.'''
    def __init__(self, server, remitente, to):
        self.server = server
        self.remitente = remitente = to
        assert type(

    def envia(self, subject, text, files=[]):
        assert type(files)==list
        msg = MIMEMultipart()
        msg['From'] = self.remitente
        msg['To'] = COMMASPACE.join(
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject 
        msg.attach( MIMEText(text) )
        for file in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(file,"rb").read() )
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        smtp = smtplib.SMTP(self.server)
        smtp.sendmail(self.remitente,, msg.as_string())



.   Facundo

More information about the Python-list mailing list