MIME attachments and SMTP

Max Møller Rasmussen maxm at normik.dk
Tue Sep 12 13:18:38 CEST 2000


here is another one that can be used. Some of the code is taken from
somebody elses program, and changed.


----------------------------------------
import string,sys,types,os,tempfile,time
import mimetypes,mimetools,MimeWriter
import smtplib

class mxmMail:

    """
    mxm_mail is an e-mail client that makes it possible to send e-mail in
the
    same way as using simple e-mail client software like outlook express or
the netscape
    mail client.
    License: TIUISICIIDC (Take it, use it, sell it, change it. I dont care.)
    contact: maxm at normik.dk, maxmcorp at worldonline.dk, maxm at mxm.dk
    """

    def __init__(self, fromName='', fromAddress='', subject='', message='',
SMTPServer='localhost'):
        self.fromName      = fromName
        self.fromAddress   = fromAddress
        self.subject       = subject
        self.message       = message
        self.recipients    = []
        self.attachments   = []
        self.SMTPServer    = SMTPServer


    def __str__(self):
        return self.message
        
    def prepend(self, text):
        """
        Prepends a string to the body.
        """
        self.message = text + self.message

    def append(self, text):
        """
        Appends a string to the body.
        """
        self.message = self.message + text


    def prependFile(self, fileName):
        """
        This method prepends the content of a text file before the body of
the message.
        One use is to add a common header file in the beginning of the
message.
        It can be done severaself.fromAddressl times to prepend different
textfiles in a specific order.
        If the file cannot be opened it wil fail silently without telling.
        This behavior is chosen so automated mailings will not be stopped by
a missing
        header/footer file
        """
        try:
            file = open(fileName)
            self.prepend(file.read())
        except:
            pass # Just fail silently
        

    def appendFile(self, fileName):
        """
        This method appends the content of a text file to the body of the
message.
        One use is to add a signature file to the end of the message.
        It can be done several times to append different textfiles in a
specific order.
        If the file cannot be opened it wil fail silently without telling.
        This behavior is chosen so automated mailings will not be stopped by
a missing
        header/footer file
        """
        try:
            file = open(fileName)
            self.append(file.read())
        except:
            pass # Just fail silently
        

    def recipientAppend(self, toName, toAddress):
        """
        Adds one more receipient to the message
        """
        self.recipients.append({'toName':toName, 'toAddress':toAddress})
        

    def setRecipients(self, recipients=[]):
        self.recipients = recipients
        

    def attachmentAppend(self, fileName):
        """
        Appends an attachment to the message. It is automatically converted
to a mime type.
        """
        self.attachments.append(fileName)
        

    def send(self):
        """
        This sends the message.
        """
        tempFileName = tempfile.mktemp()
        tempFile = open(tempFileName,'wb')
        message = MimeWriter.MimeWriter(tempFile)
        message.addheader("From", self.fromAddress)

        recipientList = []
        for recipient in self.recipients:
            recipientList.append(recipient['toAddress'])
            adressList = string.join(recipientList, '; ')

        message.addheader("To", adressList)
        message.addheader("Subject", self.subject)
        message.flushheaders()
        if len(self.attachments) == 0:
            fp = message.startbody('text/plain')
            fp.write(self.message)
        else:
            message.startmultipartbody('mixed')
            submessage = message.nextpart()
            fp = submessage.startbody('text/plain')
            fp.write(self.message)
            for attachFile in self.attachments:
                # encodes the attached files
                if type(attachFile) == types.StringType:
                    fileName = attachFile
                    filePath = attachFile
                elif type(attachFile) == types.TupleType and len(attachFile)
== 2:
                    filePath,fileName = attachFile
                else:
                    raise "Attachments Error: must be pathname string or
path,filename tuple"
                        
                submessage = message.nextpart()
                submessage.addheader("Content-Disposition", "attachment;
filename=%s" % fileName)
                ctype,prog = mimetypes.guess_type(fileName)
                if ctype == None: 
                    ctype = 'unknown/unknown'
                    
                if ctype == 'text/plain':
                    enctype = 'quoted-printable'
                else:
                    enctype = 'base64'
                submessage.addheader("Content-Transfer-Encoding",enctype)
                fp = submessage.startbody(ctype)
                afp = open(filePath,'rb')
                mimetools.encode(afp,fp,enctype)
            message.lastpart()
            
        tempFile.close()
        
        # properly formatted mime message should be in tmp file
                
        tempFile = open(tempFileName,'rb')
        msg = tempFile.read()
        tempFile.close()
        os.remove(tempFileName)
        try:
            server = smtplib.SMTP(self.SMTPServer)
            server.sendmail(self.fromAddress, recipientList, msg)
        finally:
            server.quit()

##    def save(self, fileName):
##        """
##        Saves the message to a file. Including attachements and
pre/appended files.
##        """
##        file = open(fileName, 'w')
##        file.write(str(self))











##myMsg = mxmMail('Max M', 'maxm at normik.dk', 'Here is the file you
requested', 'Just open the attached filed', 'mail.somewhere.dk')
##myMsg.prependFile('C:/root/desktop/head.txt')
##myMsg.appendFile('C:/root/desktop/sig.txt')
##myMsg.recipientAppend('Some Dude', 'maxmcorp at worldonline.dk')
##myMsg.recipientAppend('Max M', 'maxm at normik.dk')
##
##myMsg.attachmentAppend('c:/temp/file.zip')
###myMsg.attachmentAppend('C:/root/temp/cdiaz1.jpg')
###myMsg.setRecipients([{'toName':'fghdfg',
'toAddress':'fghdfg at slkdhf.com'}, {'toName':'xcvxcv',
'toAddress':'xcvxcv at cvxv.dk'}])
##
##myMsg.send()
##
###myMsg.save('C:/root/desktop/saved.txt')
##
##print myMsg
##
##print "done"




More information about the Python-list mailing list