[Twisted-Python] Mail attachments

Marcin Kasperski Marcin.Kasperski at softax.com.pl
Tue Apr 25 09:00:26 EDT 2006

> I would like to send an attachment with my email. I presume I
> do this through the sendEmail function but how to achieve is
> beyond me at the moment. :-(

Here is the code I use (to send PGN files, which are just text 
files). If you want to send images or binary files, you need to 
change the way pgn_part is constructed.

from email import Encoders
from email.Message import Message
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
#from email.MIMEImage import MIMEImage
from email.MIMEText import MIMEText

class EmailSender:
    def __init__(self, from_addr, smtp_host, 
                 smtp_user = None, smtp_password = None):
        self.from_addr = from_addr
        self.smtp_host = smtp_host
        self.smtp_user = smtp_user
        self.smtp_password = smtp_password
    def sendPGN(self, to_addr_list, subject, pgn,
                intro_text = None, 
                preamble = 'Some preamble', 
                epilogue = 'Some epilogue',
                attachment_name = 'attachmentname'):
        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = self.from_addr
        msg['To'] = ", ".join(to_addr_list)
        msg.preamble = preamble
        msg.epilogue = epilogue
        if intro_text:
            msg.attach( MIMEText(intro_text, 'plain') )
        pgn_part = MIMEBase('text', 'plain')
        pgn_part.add_header('Content-Disposition', 'attachment', 
        deferred = smtp.sendmail(self.smtp_host, self.from_addr, 
to_addr_list, msg.as_string())
        return deferred

More information about the Twisted-Python mailing list